]> git.sesse.net Git - vlc/blob - modules/gui/macosx/vout.m
String Review round one, Mac OS X interface.
[vlc] / modules / gui / macosx / vout.m
1 /*****************************************************************************
2  * vout.m: MacOS X video output module
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
5  * $Id: vout.m,v 1.69 2004/01/25 17:01:57 murray 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     vlc_value_t val;
421     intf_thread_t * p_intf;
422
423     VLCVout * o_vlv = [[VLCVout alloc] init];
424
425     if( ( i_ret = ExecuteOnMainThread( o_vlv, sel, (void *)p_vout ) ) )
426     {
427         msg_Err( p_vout, "SendRequest: no way to communicate with mt" );
428     }
429
430     [o_vlv release];
431
432     /*This makes this function dependant of the presence of a macosx 
433     interface. We do not check if this interface exists, since it has 
434     already been done before.*/
435
436     p_intf = [NSApp getIntf];
437
438     val.b_bool = VLC_TRUE;
439     var_Create(p_intf,"intf-change",VLC_VAR_BOOL);
440     var_Set(p_intf, "intf-change",val);
441
442     return( i_ret );
443 }
444
445 /*****************************************************************************
446  * CoCreateWindow: create new window 
447  *****************************************************************************
448  * Returns 0 on success, 1 otherwise
449  *****************************************************************************/
450 static int CoCreateWindow( vout_thread_t *p_vout )
451 {
452     if( CoSendRequest( p_vout, @selector(createWindow:) ) )
453     {
454         msg_Err( p_vout, "CoSendRequest (createWindow) failed" );
455         return( 1 );
456     }
457     
458     return( 0 );
459 }
460
461 /*****************************************************************************
462  * CoDestroyWindow: destroy window 
463  *****************************************************************************
464  * Returns 0 on success, 1 otherwise
465  *****************************************************************************/
466 static int CoDestroyWindow( vout_thread_t *p_vout )
467 {
468
469     VLCHideMouse( p_vout, NO );
470
471     if( CoSendRequest( p_vout, @selector(destroyWindow:) ) )
472     {
473         msg_Err( p_vout, "CoSendRequest (destroyWindow) failed" );
474         return( 1 );
475     }
476
477     return( 0 );
478 }
479
480 /*****************************************************************************
481  * CoToggleFullscreen: toggle fullscreen 
482  *****************************************************************************
483  * Returns 0 on success, 1 otherwise
484  *****************************************************************************/
485 static int CoToggleFullscreen( vout_thread_t *p_vout )
486 {
487     QTDestroySequence( p_vout );
488
489     if( CoDestroyWindow( p_vout ) )
490     {
491         msg_Err( p_vout, "unable to destroy window" );
492         return( 1 );
493     }
494     
495     p_vout->b_fullscreen = !p_vout->b_fullscreen;
496
497     if( CoCreateWindow( p_vout ) )
498     {
499         msg_Err( p_vout, "unable to create window" );
500         return( 1 );
501     }
502
503     SetPort( p_vout->p_sys->p_qdport );
504     QTScaleMatrix( p_vout );
505
506     if( QTCreateSequence( p_vout ) )
507     {
508         msg_Err( p_vout, "unable to create sequence" );
509         return( 1 ); 
510     } 
511
512     return( 0 );
513 }
514
515 /*****************************************************************************
516  * VLCHideMouse: if b_hide then hide the cursor
517  *****************************************************************************/
518 static void VLCHideMouse ( vout_thread_t *p_vout, BOOL b_hide )
519 {
520     BOOL b_inside;
521     NSRect s_rect;
522     NSPoint ml;
523     NSWindow *o_window = p_vout->p_sys->o_window;
524     NSView *o_contents = [o_window contentView];
525     
526     s_rect = [o_contents bounds];
527     ml = [o_window convertScreenToBase:[NSEvent mouseLocation]];
528     ml = [o_contents convertPoint:ml fromView:nil];
529     b_inside = [o_contents mouse: ml inRect: s_rect];
530     
531     if ( b_hide && b_inside )
532     {
533         /* only hide if mouse over VLCView */
534         [NSCursor setHiddenUntilMouseMoves: YES];
535     }
536     else if ( !b_hide )
537     {
538         [NSCursor setHiddenUntilMouseMoves: NO];
539     }
540     p_vout->p_sys->b_mouse_moved = NO;
541     p_vout->p_sys->i_time_mouse_last_moved = mdate();
542     return;
543 }
544
545 /*****************************************************************************
546  * QTScaleMatrix: scale matrix 
547  *****************************************************************************/
548 static void QTScaleMatrix( vout_thread_t *p_vout )
549 {
550     Rect s_rect;
551     unsigned int i_width, i_height;
552     Fixed factor_x, factor_y;
553     unsigned int i_offset_x = 0;
554     unsigned int i_offset_y = 0;
555
556     GetPortBounds( p_vout->p_sys->p_qdport, &s_rect );
557
558     i_width = s_rect.right - s_rect.left;
559     i_height = s_rect.bottom - s_rect.top;
560
561     if( i_height * p_vout->output.i_aspect < i_width * VOUT_ASPECT_FACTOR )
562     {
563         int i_adj_width = i_height * p_vout->output.i_aspect /
564                           VOUT_ASPECT_FACTOR;
565
566         factor_x = FixDiv( Long2Fix( i_adj_width ),
567                            Long2Fix( p_vout->output.i_width ) );
568         factor_y = FixDiv( Long2Fix( i_height ),
569                            Long2Fix( p_vout->output.i_height ) );
570
571         i_offset_x = (i_width - i_adj_width) / 2;
572     }
573     else
574     {
575         int i_adj_height = i_width * VOUT_ASPECT_FACTOR /
576                            p_vout->output.i_aspect;
577
578         factor_x = FixDiv( Long2Fix( i_width ),
579                            Long2Fix( p_vout->output.i_width ) );
580         factor_y = FixDiv( Long2Fix( i_adj_height ),
581                            Long2Fix( p_vout->output.i_height ) );
582
583         i_offset_y = (i_height - i_adj_height) / 2;
584     }
585     
586     SetIdentityMatrix( p_vout->p_sys->p_matrix );
587
588     ScaleMatrix( p_vout->p_sys->p_matrix,
589                  factor_x, factor_y,
590                  Long2Fix(0), Long2Fix(0) );            
591
592     TranslateMatrix( p_vout->p_sys->p_matrix, 
593                      Long2Fix(i_offset_x), 
594                      Long2Fix(i_offset_y) );
595
596 }
597
598 /*****************************************************************************
599  * QTCreateSequence: create a new sequence 
600  *****************************************************************************
601  * Returns 0 on success, 1 otherwise
602  *****************************************************************************/
603 static int QTCreateSequence( vout_thread_t *p_vout )
604 {
605     OSErr err;
606     ImageDescriptionPtr p_descr;
607
608     HLock( (Handle)p_vout->p_sys->h_img_descr );
609     p_descr = *p_vout->p_sys->h_img_descr;
610
611     p_descr->idSize = sizeof(ImageDescription);
612     p_descr->cType = p_vout->p_sys->i_codec;
613     p_descr->version = 1;
614     p_descr->revisionLevel = 0;
615     p_descr->vendor = 'appl';
616     p_descr->width = p_vout->output.i_width;
617     p_descr->height = p_vout->output.i_height;
618     p_descr->hRes = Long2Fix(72);
619     p_descr->vRes = Long2Fix(72);
620     p_descr->spatialQuality = codecLosslessQuality;
621     p_descr->frameCount = 1;
622     p_descr->clutID = -1;
623     p_descr->dataSize = 0;
624     p_descr->depth = 24;
625
626     HUnlock( (Handle)p_vout->p_sys->h_img_descr );
627
628     if( ( err = DecompressSequenceBeginS( 
629                               &p_vout->p_sys->i_seq,
630                               p_vout->p_sys->h_img_descr,
631                               NULL, 0,
632                               p_vout->p_sys->p_qdport,
633                               NULL, NULL,
634                               p_vout->p_sys->p_matrix,
635                               0, NULL,
636                               codecFlagUseImageBuffer,
637                               codecLosslessQuality,
638                               p_vout->p_sys->img_dc ) ) )
639     {
640         msg_Err( p_vout, "DecompressSequenceBeginS failed: %d", err );
641         return( 1 );
642     }
643
644     return( 0 );
645 }
646
647 /*****************************************************************************
648  * QTDestroySequence: destroy sequence 
649  *****************************************************************************/
650 static void QTDestroySequence( vout_thread_t *p_vout )
651 {
652     CDSequenceEnd( p_vout->p_sys->i_seq );
653 }
654
655 /*****************************************************************************
656  * QTNewPicture: allocate a picture
657  *****************************************************************************
658  * Returns 0 on success, 1 otherwise
659  *****************************************************************************/
660 static int QTNewPicture( vout_thread_t *p_vout, picture_t *p_pic )
661 {
662     int i_width  = p_vout->output.i_width;
663     int i_height = p_vout->output.i_height;
664
665     /* We know the chroma, allocate a buffer which will be used
666      * directly by the decoder */
667     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
668
669     if( p_pic->p_sys == NULL )
670     {
671         return( -1 );
672     }
673
674     switch( p_vout->output.i_chroma )
675     {
676         case VLC_FOURCC('I','4','2','0'):
677
678             p_pic->p_sys->p_info = (void *)&p_pic->p_sys->pixmap_i420;
679             p_pic->p_sys->i_size = sizeof(PlanarPixmapInfoYUV420);
680
681             /* Allocate the memory buffer */
682             p_pic->p_data = vlc_memalign( &p_pic->p_data_orig,
683                                           16, i_width * i_height * 3 / 2 );
684
685             /* Y buffer */
686             p_pic->Y_PIXELS = p_pic->p_data; 
687             p_pic->p[Y_PLANE].i_lines = i_height;
688             p_pic->p[Y_PLANE].i_pitch = i_width;
689             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
690             p_pic->p[Y_PLANE].i_visible_pitch = i_width;
691
692             /* U buffer */
693             p_pic->U_PIXELS = p_pic->Y_PIXELS + i_height * i_width;
694             p_pic->p[U_PLANE].i_lines = i_height / 2;
695             p_pic->p[U_PLANE].i_pitch = i_width / 2;
696             p_pic->p[U_PLANE].i_pixel_pitch = 1;
697             p_pic->p[U_PLANE].i_visible_pitch = i_width / 2;
698
699             /* V buffer */
700             p_pic->V_PIXELS = p_pic->U_PIXELS + i_height * i_width / 4;
701             p_pic->p[V_PLANE].i_lines = i_height / 2;
702             p_pic->p[V_PLANE].i_pitch = i_width / 2;
703             p_pic->p[V_PLANE].i_pixel_pitch = 1;
704             p_pic->p[V_PLANE].i_visible_pitch = i_width / 2;
705
706             /* We allocated 3 planes */
707             p_pic->i_planes = 3;
708
709 #define P p_pic->p_sys->pixmap_i420
710             P.componentInfoY.offset = (void *)p_pic->Y_PIXELS
711                                        - p_pic->p_sys->p_info;
712             P.componentInfoCb.offset = (void *)p_pic->U_PIXELS
713                                         - p_pic->p_sys->p_info;
714             P.componentInfoCr.offset = (void *)p_pic->V_PIXELS
715                                         - p_pic->p_sys->p_info;
716
717             P.componentInfoY.rowBytes = i_width;
718             P.componentInfoCb.rowBytes = i_width / 2;
719             P.componentInfoCr.rowBytes = i_width / 2;
720 #undef P
721
722             break;
723
724     default:
725         /* Unknown chroma, tell the guy to get lost */
726         free( p_pic->p_sys );
727         msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
728                  p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
729         p_pic->i_planes = 0;
730         return( -1 );
731     }
732
733     return( 0 );
734 }
735
736 /*****************************************************************************
737  * QTFreePicture: destroy a picture allocated with QTNewPicture
738  *****************************************************************************/
739 static void QTFreePicture( vout_thread_t *p_vout, picture_t *p_pic )
740 {
741     switch( p_vout->output.i_chroma )
742     {
743         case VLC_FOURCC('I','4','2','0'):
744             free( p_pic->p_data_orig );
745             break;
746     }
747
748     free( p_pic->p_sys );
749 }
750
751 /*****************************************************************************
752  * VLCWindow implementation
753  *****************************************************************************/
754 @implementation VLCWindow
755
756 - (void)setVout:(vout_thread_t *)_p_vout
757 {
758     p_vout = _p_vout;
759 }
760
761 - (vout_thread_t *)getVout
762 {
763     return( p_vout );
764 }
765
766 - (void)scaleWindowWithFactor: (float)factor
767 {
768     NSSize newsize;
769     int i_corrected_height, i_corrected_width;
770     NSPoint topleftbase;
771     NSPoint topleftscreen;
772     
773     if ( !p_vout->b_fullscreen )
774     {
775         topleftbase.x = 0;
776         topleftbase.y = [self frame].size.height;
777         topleftscreen = [self convertBaseToScreen: topleftbase];
778         
779         if( p_vout->output.i_height * p_vout->output.i_aspect > 
780                         p_vout->output.i_width * VOUT_ASPECT_FACTOR )
781         {
782             i_corrected_width = p_vout->output.i_height * p_vout->output.i_aspect /
783                                             VOUT_ASPECT_FACTOR;
784             newsize.width = (int) ( i_corrected_width * factor );
785             newsize.height = (int) ( p_vout->render.i_height * factor );
786         }
787         else
788         {
789             i_corrected_height = p_vout->output.i_width * VOUT_ASPECT_FACTOR /
790                                             p_vout->output.i_aspect;
791             newsize.width = (int) ( p_vout->render.i_width * factor );
792             newsize.height = (int) ( i_corrected_height * factor );
793         }
794     
795         [self setContentSize: newsize];
796         
797         [self setFrameTopLeftPoint: topleftscreen];
798         p_vout->i_changes |= VOUT_SIZE_CHANGE;
799     }
800 }
801
802 - (void)toggleFloatOnTop
803 {
804     if( config_GetInt( p_vout, "video-on-top" ) )
805     {
806         config_PutInt( p_vout, "video-on-top", 0 );
807         [p_vout->p_sys->o_window setLevel: NSNormalWindowLevel];
808     }
809     else
810     {
811         config_PutInt( p_vout, "video-on-top", 1 );
812         [p_vout->p_sys->o_window setLevel: NSStatusWindowLevel];
813     }
814 }
815
816 - (void)toggleFullscreen
817 {
818     config_PutInt(p_vout, "fullscreen", !p_vout->b_fullscreen);
819     p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
820 }
821
822 - (BOOL)isFullscreen
823 {
824     return( p_vout->b_fullscreen );
825 }
826
827 - (BOOL)canBecomeKeyWindow
828 {
829     return( YES );
830 }
831
832 - (void)keyDown:(NSEvent *)o_event
833 {
834     unichar key = 0;
835     vlc_value_t val;
836     unsigned int i_pressed_modifiers = 0;
837     val.i_int = 0;
838     
839     i_pressed_modifiers = [o_event modifierFlags];
840
841     if( i_pressed_modifiers & NSShiftKeyMask )
842         val.i_int |= KEY_MODIFIER_SHIFT;
843     if( i_pressed_modifiers & NSControlKeyMask )
844         val.i_int |= KEY_MODIFIER_CTRL;
845     if( i_pressed_modifiers & NSAlternateKeyMask )
846         val.i_int |= KEY_MODIFIER_ALT;
847     if( i_pressed_modifiers & NSCommandKeyMask )
848         val.i_int |= KEY_MODIFIER_COMMAND;
849
850     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
851
852     if( key )
853     {
854         /* Escape should always get you out of fullscreen */
855         if( key == (unichar) 0x1b )
856         {
857              if( [self isFullscreen] )
858              {
859                  [self toggleFullscreen];
860              }
861         }
862         else if ( key == ' ' )
863         {
864              playlist_t *p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
865                                                      FIND_ANYWHERE );
866              if ( p_playlist != NULL )
867              {
868                  playlist_Pause( p_playlist );
869                  vlc_object_release( p_playlist);
870              }
871         }
872         else
873         {
874             val.i_int |= CocoaKeyToVLC( key );
875             var_Set( p_vout->p_vlc, "key-pressed", val );
876         }
877     }
878     else
879     {
880         [super keyDown: o_event];
881     }
882 }
883
884 - (void)updateTitle
885 {
886     NSMutableString * o_title;
887     playlist_t * p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
888                                                        FIND_ANYWHERE );
889     
890     if( p_playlist == NULL )
891     {
892         return;
893     }
894
895     vlc_mutex_lock( &p_playlist->object_lock );
896     o_title = [NSMutableString stringWithUTF8String: 
897         p_playlist->pp_items[p_playlist->i_index]->psz_uri]; 
898     vlc_mutex_unlock( &p_playlist->object_lock );
899
900     vlc_object_release( p_playlist );
901
902     if( o_title != nil )
903     {
904         NSRange prefix_range = [o_title rangeOfString: @"file:"];
905         if( prefix_range.location != NSNotFound )
906         {
907             [o_title deleteCharactersInRange: prefix_range];
908         }
909
910         [self setTitleWithRepresentedFilename: o_title];
911     }
912     else
913     {
914         [self setTitle:
915             [NSString stringWithCString: VOUT_TITLE " (QuickTime)"]];
916     }
917 }
918
919 /* This is actually the same as VLCControls::stop. */
920 - (BOOL)windowShouldClose:(id)sender
921 {
922     playlist_t * p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
923                                                        FIND_ANYWHERE );
924     if( p_playlist == NULL )      
925     {
926         return NO;
927     }
928
929     playlist_Stop( p_playlist );
930     vlc_object_release( p_playlist );
931
932     /* The window will be closed by the intf later. */
933     return NO;
934 }
935
936 @end
937
938 /*****************************************************************************
939  * VLCView implementation
940  *****************************************************************************/
941 @implementation VLCView
942
943 - (void)drawRect:(NSRect)rect
944 {
945     vout_thread_t * p_vout;
946     id o_window = [self window];
947     p_vout = (vout_thread_t *)[o_window getVout];
948     
949     [[NSColor blackColor] set];
950     NSRectFill( rect );
951     [super drawRect: rect];
952
953     p_vout->i_changes |= VOUT_SIZE_CHANGE;
954 }
955
956 - (BOOL)acceptsFirstResponder
957 {
958     return( YES );
959 }
960
961 - (BOOL)becomeFirstResponder
962 {
963     vout_thread_t * p_vout;
964     id o_window = [self window];
965     p_vout = (vout_thread_t *)[o_window getVout];
966     
967     [o_window setAcceptsMouseMovedEvents: YES];
968     return( YES );
969 }
970
971 - (BOOL)resignFirstResponder
972 {
973     vout_thread_t * p_vout;
974     id o_window = [self window];
975     p_vout = (vout_thread_t *)[o_window getVout];
976     
977     [o_window setAcceptsMouseMovedEvents: NO];
978     VLCHideMouse( p_vout, NO );
979     return( YES );
980 }
981
982 - (void)mouseDown:(NSEvent *)o_event
983 {
984     vout_thread_t * p_vout;
985     id o_window = [self window];
986     p_vout = (vout_thread_t *)[o_window getVout];
987     vlc_value_t val;
988
989     switch( [o_event type] )
990     {        
991         case NSLeftMouseDown:
992         {
993             var_Get( p_vout, "mouse-button-down", &val );
994             val.i_int |= 1;
995             var_Set( p_vout, "mouse-button-down", val );
996         }
997         break;
998         
999         default:
1000             [super mouseDown: o_event];
1001         break;
1002     }
1003 }
1004
1005 - (void)otherMouseDown:(NSEvent *)o_event
1006 {
1007     /* This is not the the wheel button. you need to poll the
1008      * mouseWheel event for that. other is a third, forth or fifth button */
1009     vout_thread_t * p_vout;
1010     id o_window = [self window];
1011     p_vout = (vout_thread_t *)[o_window getVout];
1012     vlc_value_t val;
1013
1014     switch( [o_event type] )
1015     {
1016         case NSOtherMouseDown:
1017         {
1018             var_Get( p_vout, "mouse-button-down", &val );
1019             val.i_int |= 2;
1020             var_Set( p_vout, "mouse-button-down", val );
1021         }
1022         break;
1023         
1024         default:
1025             [super mouseDown: o_event];
1026         break;
1027     }
1028 }
1029
1030 - (void)rightMouseDown:(NSEvent *)o_event
1031 {
1032     vout_thread_t * p_vout;
1033     id o_window = [self window];
1034     p_vout = (vout_thread_t *)[o_window getVout];
1035     vlc_value_t val;
1036
1037     switch( [o_event type] )
1038     {
1039         case NSRightMouseDown:
1040         {
1041             var_Get( p_vout, "mouse-button-down", &val );
1042             val.i_int |= 4;
1043             var_Set( p_vout, "mouse-button-down", val );
1044         }
1045         break;
1046         
1047         default:
1048             [super mouseDown: o_event];
1049         break;
1050     }
1051 }
1052
1053 - (void)mouseUp:(NSEvent *)o_event
1054 {
1055     vout_thread_t * p_vout;
1056     id o_window = [self window];
1057     p_vout = (vout_thread_t *)[o_window getVout];
1058     vlc_value_t val;
1059
1060     switch( [o_event type] )
1061     {
1062         case NSLeftMouseUp:
1063         {
1064             vlc_value_t b_val;
1065             b_val.b_bool = VLC_TRUE;
1066             var_Set( p_vout, "mouse-clicked", b_val );
1067             
1068             var_Get( p_vout, "mouse-button-down", &val );
1069             val.i_int &= ~1;
1070             var_Set( p_vout, "mouse-button-down", val );
1071         }
1072         break;
1073                 
1074         default:
1075             [super mouseUp: o_event];
1076         break;
1077     }
1078 }
1079
1080 - (void)otherMouseUp:(NSEvent *)o_event
1081 {
1082     vout_thread_t * p_vout;
1083     id o_window = [self window];
1084     p_vout = (vout_thread_t *)[o_window getVout];
1085     vlc_value_t val;
1086
1087     switch( [o_event type] )
1088     {
1089         case NSOtherMouseUp:
1090         {
1091             var_Get( p_vout, "mouse-button-down", &val );
1092             val.i_int &= ~2;
1093             var_Set( p_vout, "mouse-button-down", val );
1094         }
1095         break;
1096                 
1097         default:
1098             [super mouseUp: o_event];
1099         break;
1100     }
1101 }
1102
1103 - (void)rightMouseUp:(NSEvent *)o_event
1104 {
1105     vout_thread_t * p_vout;
1106     id o_window = [self window];
1107     p_vout = (vout_thread_t *)[o_window getVout];
1108     vlc_value_t val;
1109
1110     switch( [o_event type] )
1111     {
1112         case NSRightMouseUp:
1113         {
1114             var_Get( p_vout, "mouse-button-down", &val );
1115             val.i_int &= ~4;
1116             var_Set( p_vout, "mouse-button-down", val );
1117         }
1118         break;
1119         
1120         default:
1121             [super mouseUp: o_event];
1122         break;
1123     }
1124 }
1125
1126 - (void)mouseDragged:(NSEvent *)o_event
1127 {
1128     [self mouseMoved:o_event];
1129 }
1130
1131 - (void)otherMouseDragged:(NSEvent *)o_event
1132 {
1133     [self mouseMoved:o_event];
1134 }
1135
1136 - (void)rightMouseDragged:(NSEvent *)o_event
1137 {
1138     [self mouseMoved:o_event];
1139 }
1140
1141 - (void)mouseMoved:(NSEvent *)o_event
1142 {
1143     NSPoint ml;
1144     NSRect s_rect;
1145     BOOL b_inside;
1146
1147     vout_thread_t * p_vout;
1148     id o_window = [self window];
1149     p_vout = (vout_thread_t *)[o_window getVout];
1150
1151     s_rect = [self bounds];
1152     ml = [self convertPoint: [o_event locationInWindow] fromView: nil];
1153     b_inside = [self mouse: ml inRect: s_rect];
1154
1155     if( b_inside )
1156     {
1157         vlc_value_t val;
1158         int i_width, i_height, i_x, i_y;
1159         
1160         vout_PlacePicture( p_vout, (unsigned int)s_rect.size.width,
1161                                    (unsigned int)s_rect.size.height,
1162                                    &i_x, &i_y, &i_width, &i_height );
1163
1164         val.i_int = ( ((int)ml.x) - i_x ) * 
1165                     p_vout->render.i_width / i_width;
1166         var_Set( p_vout, "mouse-x", val );
1167
1168         val.i_int = ( ((int)ml.y) - i_y ) * 
1169                     p_vout->render.i_height / i_height;
1170         var_Set( p_vout, "mouse-y", val );
1171             
1172         val.b_bool = VLC_TRUE;
1173         var_Set( p_vout, "mouse-moved", val );
1174         p_vout->p_sys->i_time_mouse_last_moved = mdate();
1175         p_vout->p_sys->b_mouse_moved = YES;
1176     }
1177
1178     [super mouseMoved: o_event];
1179 }
1180
1181 @end
1182
1183 /*****************************************************************************
1184  * VLCVout implementation
1185  *****************************************************************************/
1186 @implementation VLCVout
1187
1188 - (void)createWindow:(NSValue *)o_value
1189 {
1190     vlc_value_t val;
1191     VLCView * o_view;
1192     NSScreen * o_screen;
1193     vout_thread_t * p_vout;
1194     vlc_bool_t b_main_screen;
1195     
1196     p_vout = (vout_thread_t *)[o_value pointerValue];
1197
1198     p_vout->p_sys->o_window = [VLCWindow alloc];
1199     [p_vout->p_sys->o_window setVout: p_vout];
1200     [p_vout->p_sys->o_window setReleasedWhenClosed: YES];
1201
1202     if( var_Get( p_vout, "video-device", &val ) < 0 )
1203     {
1204         o_screen = [NSScreen mainScreen];
1205         b_main_screen = 1;
1206     }
1207     else
1208     {
1209         NSArray *o_screens = [NSScreen screens];
1210         unsigned int i_index = val.i_int;
1211         
1212         if( [o_screens count] < i_index )
1213         {
1214             o_screen = [NSScreen mainScreen];
1215             b_main_screen = 1;
1216         }
1217         else
1218         {
1219             i_index--;
1220             o_screen = [o_screens objectAtIndex: i_index];
1221             config_PutInt( p_vout, "macosx-vdev", i_index );
1222             b_main_screen = (i_index == 0);
1223         }
1224     } 
1225
1226     if( p_vout->b_fullscreen )
1227     {
1228         NSRect screen_rect = [o_screen frame];
1229         screen_rect.origin.x = screen_rect.origin.y = 0;
1230
1231         if ( b_main_screen && p_vout->p_sys->p_fullscreen_state == NULL )
1232             BeginFullScreen( &p_vout->p_sys->p_fullscreen_state, NULL, 0, 0,
1233                              NULL, NULL, fullScreenAllowEvents );
1234
1235         [p_vout->p_sys->o_window 
1236             initWithContentRect: screen_rect
1237             styleMask: NSBorderlessWindowMask
1238             backing: NSBackingStoreBuffered
1239             defer: NO screen: o_screen];
1240
1241         //[p_vout->p_sys->o_window setLevel: NSPopUpMenuWindowLevel - 1];
1242         p_vout->p_sys->b_mouse_moved = YES;
1243         p_vout->p_sys->i_time_mouse_last_moved = mdate();
1244     }
1245     else
1246     {
1247         unsigned int i_stylemask = NSTitledWindowMask |
1248                                    NSMiniaturizableWindowMask |
1249                                    NSClosableWindowMask |
1250                                    NSResizableWindowMask;
1251         
1252         if ( p_vout->p_sys->p_fullscreen_state != NULL )
1253             EndFullScreen ( p_vout->p_sys->p_fullscreen_state, NULL );
1254         p_vout->p_sys->p_fullscreen_state = NULL;
1255
1256         [p_vout->p_sys->o_window 
1257             initWithContentRect: p_vout->p_sys->s_rect
1258             styleMask: i_stylemask
1259             backing: NSBackingStoreBuffered
1260             defer: NO screen: o_screen];
1261
1262         [p_vout->p_sys->o_window setAlphaValue: config_GetFloat( p_vout, "macosx-opaqueness" )];
1263         
1264         if( config_GetInt( p_vout, "video-on-top" ) )
1265         {
1266             [p_vout->p_sys->o_window setLevel: NSStatusWindowLevel];
1267         }
1268         
1269         if( !p_vout->p_sys->b_pos_saved )   
1270         {
1271             [p_vout->p_sys->o_window center];
1272         }
1273     }
1274
1275     o_view = [[VLCView alloc] init];
1276     /* FIXME: [o_view setMenu:] */
1277     [p_vout->p_sys->o_window setContentView: o_view];
1278     [o_view autorelease];
1279
1280     [o_view lockFocus];
1281     p_vout->p_sys->p_qdport = [o_view qdPort];
1282
1283     [o_view unlockFocus];
1284     
1285     [p_vout->p_sys->o_window updateTitle];
1286     [p_vout->p_sys->o_window makeKeyAndOrderFront: nil];
1287
1288 }
1289
1290 - (void)destroyWindow:(NSValue *)o_value
1291 {
1292     vout_thread_t * p_vout;
1293
1294     p_vout = (vout_thread_t *)[o_value pointerValue];
1295
1296     if( !p_vout->b_fullscreen )
1297     {
1298         NSRect s_rect;
1299
1300         s_rect = [[p_vout->p_sys->o_window contentView] frame];
1301         p_vout->p_sys->s_rect.size = s_rect.size;
1302
1303         s_rect = [p_vout->p_sys->o_window frame];
1304         p_vout->p_sys->s_rect.origin = s_rect.origin;
1305
1306         p_vout->p_sys->b_pos_saved = YES;
1307     }
1308     
1309     p_vout->p_sys->p_qdport = nil;
1310     [p_vout->p_sys->o_window close];
1311     p_vout->p_sys->o_window = nil;
1312 }
1313
1314 @end