f7f5979a05dee7395c3e39975455453f93c623da
[vlc.git] / modules / gui / beos / VideoOutput.cpp
1 /*****************************************************************************
2  * vout_beos.cpp: beos video output display method
3  *****************************************************************************
4  * Copyright (C) 2000, 2001 VideoLAN
5  * $Id: VideoOutput.cpp,v 1.20 2003/06/03 12:06:29 titer Exp $
6  *
7  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Tony Castley <tcastley@mail.powerup.com.au>
10  *          Richard Shepherd <richard@rshepherd.demon.co.uk>
11  *          Stephan Aßmus <stippi@yellowbites.com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  * 
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
26  *****************************************************************************/
27
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 #include <errno.h>                                                 /* ENOMEM */
32 #include <stdlib.h>                                                /* free() */
33 #include <stdio.h>
34 #include <string.h>                                            /* strerror() */
35
36 #include <Application.h>
37 #include <BitmapStream.h>
38 #include <Bitmap.h>
39 #include <Directory.h>
40 #include <DirectWindow.h>
41 #include <File.h>
42 #include <InterfaceKit.h>
43 #include <NodeInfo.h>
44 #include <String.h>
45 #include <TranslatorRoster.h>
46 #include <WindowScreen.h>
47
48 /* VLC headers */
49 #include <vlc/vlc.h>
50 #include <vlc/intf.h>
51 #include <vlc/vout.h>
52
53 #include "InterfaceWindow.h"    // for load/save_settings()
54 #include "DrawingTidbits.h"
55 #include "MsgVals.h"
56
57 #include "VideoWindow.h"
58
59 /*****************************************************************************
60  * vout_sys_t: BeOS video output method descriptor
61  *****************************************************************************
62  * This structure is part of the video output thread descriptor.
63  * It describes the BeOS specific properties of an output thread.
64  *****************************************************************************/
65 struct vout_sys_t
66 {
67     VideoWindow *  p_window;
68
69     s32 i_width;
70     s32 i_height;
71
72 //    u8 *pp_buffer[3];
73     u32 source_chroma;
74     int i_index;
75
76 };
77
78 #define MOUSE_IDLE_TIMEOUT 2000000      // two seconds
79 #define MIN_AUTO_VSYNC_REFRESH 61       // Hz
80 #define DEFAULT_SCREEN_SHOT_FORMAT 'PNG '
81 #define DEFAULT_SCREEN_SHOT_PATH "/boot/home/vlc screenshot"
82
83 /*****************************************************************************
84  * beos_GetAppWindow : retrieve a BWindow pointer from the window name
85  *****************************************************************************/
86 BWindow*
87 beos_GetAppWindow(char *name)
88 {
89     int32       index;
90     BWindow     *window;
91     
92     for (index = 0 ; ; index++)
93     {
94         window = be_app->WindowAt(index);
95         if (window == NULL)
96             break;
97         if (window->LockWithTimeout(20000) == B_OK)
98         {
99             if (strcmp(window->Name(), name) == 0)
100             {
101                 window->Unlock();
102                 break;
103             }
104             window->Unlock();
105         }
106     }
107     return window; 
108 }
109
110 /*****************************************************************************
111  * get_interface_window
112  *****************************************************************************/
113 BWindow*
114 get_interface_window()
115 {
116         return beos_GetAppWindow( "VLC " PACKAGE_VERSION );
117 }
118
119 class BackgroundView : public BView
120 {
121  public:
122                                                         BackgroundView(BRect frame, VLCView* view)
123                                                         : BView(frame, "background",
124                                                                         B_FOLLOW_ALL, B_FULL_UPDATE_ON_RESIZE),
125                                                           fVideoView(view)
126                                                         {
127                                                                 SetViewColor(kBlack);
128                                                         }
129         virtual                                 ~BackgroundView() {}
130
131         virtual void                    MouseDown(BPoint where)
132                                                         {
133                                                                 // convert coordinates
134                                                                 where = fVideoView->ConvertFromParent(where);
135                                                                 // let him handle it
136                                                                 fVideoView->MouseDown(where);
137                                                         }
138         virtual void                    MouseMoved(BPoint where, uint32 transit,
139                                                                            const BMessage* dragMessage)
140                                                         {
141                                                                 // convert coordinates
142                                                                 where = fVideoView->ConvertFromParent(where);
143                                                                 // let him handle it
144                                                                 fVideoView->MouseMoved(where, transit, dragMessage);
145                                                                 // notice: It might look like transit should be
146                                                                 // B_OUTSIDE_VIEW regardless, but leave it like this,
147                                                                 // otherwise, unwanted things will happen!
148                                                         }
149
150  private:
151         VLCView*                                fVideoView;
152 };
153
154
155 /*****************************************************************************
156  * VideoSettings constructor and destructor
157  *****************************************************************************/
158 VideoSettings::VideoSettings()
159         : fVideoSize( SIZE_100 ),
160           fFlags( FLAG_CORRECT_RATIO ),
161           fSettings( new BMessage( 'sett' ) )
162 {
163         // read settings from disk
164         status_t ret = load_settings( fSettings, "video_settings", "VideoLAN Client" );
165         if ( ret == B_OK )
166         {
167                 uint32 flags;
168                 if ( fSettings->FindInt32( "flags", (int32*)&flags ) == B_OK )
169                         SetFlags( flags );
170                 uint32 size;
171                 if ( fSettings->FindInt32( "video size", (int32*)&size ) == B_OK )
172                         SetVideoSize( size );
173         }
174         else
175         {
176                 fprintf( stderr, "error loading video settings: %s\n", strerror( ret ) );
177                 
178                 // figure out if we should use vertical sync by default
179                 BScreen screen(B_MAIN_SCREEN_ID);
180                 if (screen.IsValid())
181                 {
182                         display_mode mode; 
183                         screen.GetMode(&mode); 
184                         float refresh = (mode.timing.pixel_clock * 1000)
185                                                         / ((mode.timing.h_total)* (mode.timing.v_total)); 
186                         if (refresh < MIN_AUTO_VSYNC_REFRESH)
187                                 AddFlags(FLAG_SYNC_RETRACE);
188                 }
189         }
190 }
191
192 VideoSettings::VideoSettings( const VideoSettings& clone )
193         : fVideoSize( clone.VideoSize() ),
194           fFlags( clone.Flags() ),
195           fSettings( NULL )
196 {
197 }
198
199
200 VideoSettings::~VideoSettings()
201 {
202         if ( fSettings )
203         {
204                 // we are the default settings
205                 // and write our settings to disk
206                 if (fSettings->ReplaceInt32( "video size", VideoSize() ) != B_OK)
207                         fSettings->AddInt32( "video size", VideoSize() );
208                 if (fSettings->ReplaceInt32( "flags", Flags() ) != B_OK)
209                         fSettings->AddInt32( "flags", Flags() );
210
211                 status_t ret = save_settings( fSettings, "video_settings", "VideoLAN Client" );
212                 if ( ret != B_OK )
213                         fprintf( stderr, "error saving video settings: %s\n", strerror( ret ) );
214                 delete fSettings;
215         }
216         else
217         {
218                 // we are just a clone of the default settings
219                 fDefaultSettings.SetVideoSize( VideoSize() );
220                 fDefaultSettings.SetFlags( Flags() );
221         }
222 }
223
224 /*****************************************************************************
225  * VideoSettings::DefaultSettings
226  *****************************************************************************/
227 VideoSettings*
228 VideoSettings::DefaultSettings()
229 {
230         return &fDefaultSettings;
231 }
232
233 /*****************************************************************************
234  * VideoSettings::SetVideoSize
235  *****************************************************************************/
236 void
237 VideoSettings::SetVideoSize( uint32 mode )
238 {
239         fVideoSize = mode;
240 }
241
242 // static variable initialization
243 VideoSettings
244 VideoSettings::fDefaultSettings;
245
246
247 /*****************************************************************************
248  * VideoWindow constructor and destructor
249  *****************************************************************************/
250 VideoWindow::VideoWindow(int v_width, int v_height, BRect frame,
251                          vout_thread_t *p_videoout)
252         : BWindow(frame, NULL, B_TITLED_WINDOW, B_NOT_CLOSABLE | B_NOT_MINIMIZABLE),
253           i_width(frame.IntegerWidth()),
254           i_height(frame.IntegerHeight()),
255           winSize(frame),
256           i_buffer(0),
257           teardownwindow(false),
258           fTrueWidth(v_width),
259           fTrueHeight(v_height),
260           fCachedFeel(B_NORMAL_WINDOW_FEEL),
261           fInterfaceShowing(false),
262           fInitStatus(B_ERROR),
263           fSettings(new VideoSettings(*VideoSettings::DefaultSettings()))
264 {
265     p_vout = p_videoout;
266     
267     // create the view to do the display
268     view = new VLCView( Bounds(), p_vout );
269
270         // create background view
271     BView *mainView =  new BackgroundView( Bounds(), view );
272     AddChild(mainView);
273     mainView->AddChild(view);
274
275         // allocate bitmap buffers
276         for (int32 i = 0; i < 3; i++)
277                 bitmap[i] = NULL;
278         fInitStatus = _AllocateBuffers(v_width, v_height, &mode);
279
280         // make sure we layout the view correctly
281     FrameResized(i_width, i_height);
282
283     if (fInitStatus >= B_OK && mode == OVERLAY)
284     {
285        overlay_restrictions r;
286
287        bitmap[1]->GetOverlayRestrictions(&r);
288        SetSizeLimits((i_width * r.min_width_scale), i_width * r.max_width_scale,
289                      (i_height * r.min_height_scale), i_height * r.max_height_scale);
290     }
291     
292         // vlc settings override settings from disk
293         if (config_GetInt(p_vout, "fullscreen"))
294                 fSettings->AddFlags(VideoSettings::FLAG_FULL_SCREEN);
295
296     // add a few useful shortcuts
297     AddShortcut( 'f', 0, new BMessage( TOGGLE_FULL_SCREEN ) );
298     AddShortcut( '1', 0, new BMessage( RESIZE_50 ) );
299     AddShortcut( '2', 0, new BMessage( RESIZE_100 ) );
300     AddShortcut( '3', 0, new BMessage( RESIZE_200 ) );
301     
302     // workaround for french keyboards
303     AddShortcut( '&', 0, new BMessage( RESIZE_50 ) );
304     AddShortcut( 'é', 0, new BMessage( RESIZE_100 ) );
305         // FIXME - this one doesn't work because 'é' is a multi-byte character
306     AddShortcut( '"', 0, new BMessage( RESIZE_200 ) );
307     
308     _SetToSettings();
309 }
310
311 VideoWindow::~VideoWindow()
312 {
313     int32 result;
314
315     teardownwindow = true;
316     wait_for_thread(fDrawThreadID, &result);
317     _FreeBuffers();
318         delete fSettings;
319 }
320
321 /*****************************************************************************
322  * VideoWindow::MessageReceived
323  *****************************************************************************/
324 void
325 VideoWindow::MessageReceived( BMessage *p_message )
326 {
327         switch( p_message->what )
328         {
329             case SHOW_INTERFACE:
330                 SetInterfaceShowing( true );
331                 break;
332                 case TOGGLE_FULL_SCREEN:
333                         BWindow::Zoom();
334                         break;
335                 case RESIZE_50:
336                 case RESIZE_100:
337                 case RESIZE_200:
338                         if (IsFullScreen())
339                                 BWindow::Zoom();
340                         _SetVideoSize(p_message->what);
341                         break;
342                 case VERT_SYNC:
343                         SetSyncToRetrace(!IsSyncedToRetrace());
344                         break;
345                 case WINDOW_FEEL:
346                         {
347                                 window_feel winFeel;
348                                 if (p_message->FindInt32("WinFeel", (int32*)&winFeel) == B_OK)
349                                 {
350                                         SetFeel(winFeel);
351                                         fCachedFeel = winFeel;
352                                         if (winFeel == B_FLOATING_ALL_WINDOW_FEEL)
353                                                 fSettings->AddFlags(VideoSettings::FLAG_ON_TOP_ALL);
354                                         else
355                                                 fSettings->ClearFlags(VideoSettings::FLAG_ON_TOP_ALL);
356                                 }
357                         }
358                         break;
359                 case ASPECT_CORRECT:
360                         SetCorrectAspectRatio(!CorrectAspectRatio());
361                         break;
362                 case SCREEN_SHOT:
363                         // save a screen shot
364                         if ( BBitmap* current = bitmap[i_buffer] )
365                         {
366 // the following line might be tempting, but does not work for some overlay bitmaps!!!
367 //                              BBitmap* temp = new BBitmap( current );
368 // so we clone the bitmap ourselves
369 // however, we need to take care of potentially different padding!
370 // memcpy() is slow when reading from grafix memory, but what the heck...
371                                 BBitmap* temp = new BBitmap( current->Bounds(), current->ColorSpace() );
372                                 if ( temp && temp->IsValid() )
373                                 {
374                                         int32 height = (int32)current->Bounds().Height();
375                                         uint8* dst = (uint8*)temp->Bits();
376                                         uint8* src = (uint8*)current->Bits();
377                                         int32 dstBpr = temp->BytesPerRow();
378                                         int32 srcBpr = current->BytesPerRow();
379                                         int32 validBytes = dstBpr > srcBpr ? srcBpr : dstBpr;
380                                         for ( int32 y = 0; y < height; y++ )
381                                         {
382                                                 memcpy( dst, src, validBytes );
383                                                 dst += dstBpr;
384                                                 src += srcBpr;
385                                         }
386                                         char * path = config_GetPsz( p_vout, "beos-screenshotpath" );
387                                         if ( !path )
388                                                 path = strdup( DEFAULT_SCREEN_SHOT_PATH );
389                                         
390                                         /* FIXME - we should check which translators are
391                                            actually available */
392                                         char * psz_format = config_GetPsz( p_vout, "beos-screenshotformat" );
393                                         int32 format = DEFAULT_SCREEN_SHOT_FORMAT;
394                                         if( !strcmp( psz_format, "TGA" ) )
395                                                 format = 'TGA ';
396                                         else if( !strcmp( psz_format, "PPM" ) )
397                                                 format = 'PPM ';
398                                         else if( !strcmp( psz_format, "JPEG" ) )
399                                                 format = 'JPEG';
400                                         else if( !strcmp( psz_format, "BMP" ) )
401                                                 format = 'BMP ';
402
403                                         _SaveScreenShot( temp, path, format );
404                                 }
405                                 else
406                                 {
407                                         delete temp;
408                                 }
409                         }
410                         break;
411                 default:
412                         BWindow::MessageReceived( p_message );
413                         break;
414         }
415 }
416
417 /*****************************************************************************
418  * VideoWindow::Zoom
419  *****************************************************************************/
420 void
421 VideoWindow::Zoom(BPoint origin, float width, float height )
422 {
423         ToggleFullScreen();
424 }
425
426 /*****************************************************************************
427  * VideoWindow::FrameMoved
428  *****************************************************************************/
429 void
430 VideoWindow::FrameMoved(BPoint origin) 
431 {
432         if (IsFullScreen())
433                 return ;
434         winSize = Frame();
435 }
436
437 /*****************************************************************************
438  * VideoWindow::FrameResized
439  *****************************************************************************/
440 void
441 VideoWindow::FrameResized( float width, float height )
442 {
443         int32 useWidth = CorrectAspectRatio() ? i_width : fTrueWidth;
444         int32 useHeight = CorrectAspectRatio() ? i_height : fTrueHeight;
445     float out_width, out_height;
446     float out_left, out_top;
447     float width_scale = width / useWidth;
448     float height_scale = height / useHeight;
449
450     if (width_scale <= height_scale)
451     {
452         out_width = (useWidth * width_scale);
453         out_height = (useHeight * width_scale);
454         out_left = 0; 
455         out_top = (height - out_height) / 2;
456     }
457     else   /* if the height is proportionally smaller */
458     {
459         out_width = (useWidth * height_scale);
460         out_height = (useHeight * height_scale);
461         out_top = 0;
462         out_left = (width - out_width) / 2;
463     }
464     view->MoveTo(out_left,out_top);
465     view->ResizeTo(out_width, out_height);
466
467         if (!IsFullScreen())
468         winSize = Frame();
469 }
470
471 /*****************************************************************************
472  * VideoWindow::ScreenChanged
473  *****************************************************************************/
474 void
475 VideoWindow::ScreenChanged(BRect frame, color_space format)
476 {
477         BScreen screen(this);
478         display_mode mode; 
479         screen.GetMode(&mode); 
480         float refresh = (mode.timing.pixel_clock * 1000)
481                                         / ((mode.timing.h_total) * (mode.timing.v_total)); 
482         SetSyncToRetrace(refresh < MIN_AUTO_VSYNC_REFRESH);
483 }
484
485 /*****************************************************************************
486  * VideoWindow::Activate
487  *****************************************************************************/
488 void
489 VideoWindow::WindowActivated(bool active)
490 {
491 }
492
493 /*****************************************************************************
494  * VideoWindow::drawBuffer
495  *****************************************************************************/
496 void
497 VideoWindow::drawBuffer(int bufferIndex)
498 {
499     i_buffer = bufferIndex;
500
501     // sync to the screen if required
502     if (IsSyncedToRetrace())
503     {
504         BScreen screen(this);
505         screen.WaitForRetrace(22000);
506     }
507     if (fInitStatus >= B_OK && LockLooper())
508     {
509        // switch the overlay bitmap
510        if (mode == OVERLAY)
511        {
512           rgb_color key;
513           view->SetViewOverlay(bitmap[i_buffer], 
514                             bitmap[i_buffer]->Bounds() ,
515                             view->Bounds(),
516                             &key, B_FOLLOW_ALL,
517                                                         B_OVERLAY_FILTER_HORIZONTAL|B_OVERLAY_FILTER_VERTICAL|
518                                     B_OVERLAY_TRANSFER_CHANNEL);
519                    view->SetViewColor(key);
520            }
521        else
522        {
523          // switch the bitmap
524          view->DrawBitmap(bitmap[i_buffer], view->Bounds() );
525        }
526        UnlockLooper();
527     }
528 }
529
530 /*****************************************************************************
531  * VideoWindow::SetInterfaceShowing
532  *****************************************************************************/
533 void
534 VideoWindow::ToggleInterfaceShowing()
535 {
536         SetInterfaceShowing(!fInterfaceShowing);
537 }
538
539 /*****************************************************************************
540  * VideoWindow::SetInterfaceShowing
541  *****************************************************************************/
542 void
543 VideoWindow::SetInterfaceShowing(bool showIt)
544 {
545         BWindow* window = get_interface_window();
546         if (window)
547         {
548                 if (showIt)
549                 {
550                         if (fCachedFeel != B_NORMAL_WINDOW_FEEL)
551                                 SetFeel(B_NORMAL_WINDOW_FEEL);
552                         window->Activate(true);
553                         SendBehind(window);
554                 }
555                 else
556                 {
557                         SetFeel(fCachedFeel);
558                         Activate(true);
559                         window->SendBehind(this);
560                 }
561                 fInterfaceShowing = showIt;
562         }
563 }
564
565 /*****************************************************************************
566  * VideoWindow::SetCorrectAspectRatio
567  *****************************************************************************/
568 void
569 VideoWindow::SetCorrectAspectRatio(bool doIt)
570 {
571         if (CorrectAspectRatio() != doIt)
572         {
573                 if (doIt)
574                         fSettings->AddFlags(VideoSettings::FLAG_CORRECT_RATIO);
575                 else
576                         fSettings->ClearFlags(VideoSettings::FLAG_CORRECT_RATIO);
577                 FrameResized(Bounds().Width(), Bounds().Height());
578         }
579 }
580
581 /*****************************************************************************
582  * VideoWindow::CorrectAspectRatio
583  *****************************************************************************/
584 bool
585 VideoWindow::CorrectAspectRatio() const
586 {
587         return fSettings->HasFlags(VideoSettings::FLAG_CORRECT_RATIO);
588 }
589
590 /*****************************************************************************
591  * VideoWindow::ToggleFullScreen
592  *****************************************************************************/
593 void
594 VideoWindow::ToggleFullScreen()
595 {
596         SetFullScreen(!IsFullScreen());
597 }
598
599 /*****************************************************************************
600  * VideoWindow::SetFullScreen
601  *****************************************************************************/
602 void
603 VideoWindow::SetFullScreen(bool doIt)
604 {
605         if (doIt)
606         {
607                 BScreen screen(this);
608                 BRect rect = screen.Frame();
609                 Activate();
610                 MoveTo(0.0, 0.0);
611                 ResizeTo(rect.IntegerWidth(), rect.IntegerHeight());
612                 be_app->ObscureCursor();
613                 fInterfaceShowing = false;
614                 fSettings->AddFlags(VideoSettings::FLAG_FULL_SCREEN);
615         }
616         else
617         {
618                 MoveTo(winSize.left, winSize.top);
619                 ResizeTo(winSize.IntegerWidth(), winSize.IntegerHeight());
620                 be_app->ShowCursor();
621                 fInterfaceShowing = true;
622                 fSettings->ClearFlags(VideoSettings::FLAG_FULL_SCREEN);
623         }
624 }
625
626 /*****************************************************************************
627  * VideoWindow::IsFullScreen
628  *****************************************************************************/
629 bool
630 VideoWindow::IsFullScreen() const
631 {
632         return fSettings->HasFlags(VideoSettings::FLAG_FULL_SCREEN);
633 }
634
635 /*****************************************************************************
636  * VideoWindow::SetSyncToRetrace
637  *****************************************************************************/
638 void
639 VideoWindow::SetSyncToRetrace(bool doIt)
640 {
641         if (doIt)
642                 fSettings->AddFlags(VideoSettings::FLAG_SYNC_RETRACE);
643         else
644                 fSettings->ClearFlags(VideoSettings::FLAG_SYNC_RETRACE);
645 }
646
647 /*****************************************************************************
648  * VideoWindow::IsSyncedToRetrace
649  *****************************************************************************/
650 bool
651 VideoWindow::IsSyncedToRetrace() const
652 {
653         return fSettings->HasFlags(VideoSettings::FLAG_SYNC_RETRACE);
654 }
655
656
657 /*****************************************************************************
658  * VideoWindow::_AllocateBuffers
659  *****************************************************************************/
660 status_t
661 VideoWindow::_AllocateBuffers(int width, int height, int* mode)
662 {
663         // clear any old buffers
664         _FreeBuffers();
665         // set default mode
666         *mode = BITMAP;
667
668         BRect bitmapFrame( 0, 0, width, height );
669         // read from config, if we are supposed to use overlay at all
670     int noOverlay = !config_GetInt( p_vout, "overlay" );
671         // test for overlay capability
672     for (int i = 0; i < COLOR_COUNT; i++)
673     {
674         if (noOverlay) break;
675         bitmap[0] = new BBitmap ( bitmapFrame, 
676                                   B_BITMAP_WILL_OVERLAY |
677                                   B_BITMAP_RESERVE_OVERLAY_CHANNEL,
678                                   colspace[i].colspace);
679
680         if(bitmap[0] && bitmap[0]->InitCheck() == B_OK) 
681         {
682             colspace_index = i;
683
684             bitmap[1] = new BBitmap( bitmapFrame, B_BITMAP_WILL_OVERLAY,
685                                      colspace[colspace_index].colspace);
686             bitmap[2] = new BBitmap( bitmapFrame, B_BITMAP_WILL_OVERLAY,
687                                      colspace[colspace_index].colspace);
688             if ( (bitmap[2] && bitmap[2]->InitCheck() == B_OK) )
689             {
690                *mode = OVERLAY;
691                rgb_color key;
692                view->SetViewOverlay(bitmap[0], 
693                                     bitmap[0]->Bounds() ,
694                                     view->Bounds(),
695                                     &key, B_FOLLOW_ALL,
696                                             B_OVERLAY_FILTER_HORIZONTAL|B_OVERLAY_FILTER_VERTICAL);
697                        view->SetViewColor(key);
698                SetTitle("VLC " PACKAGE_VERSION " (Overlay)");
699                break;
700             }
701             else
702             {
703                _FreeBuffers();
704                *mode = BITMAP; // might want to try again with normal bitmaps
705             }
706         }
707         else
708             delete bitmap[0];
709         }
710
711     if (*mode == BITMAP)
712         {
713         // fallback to RGB
714         colspace_index = DEFAULT_COL;   // B_RGB32
715         SetTitle( "VLC " PACKAGE_VERSION " (Bitmap)" );
716         bitmap[0] = new BBitmap( bitmapFrame, colspace[colspace_index].colspace );
717         bitmap[1] = new BBitmap( bitmapFrame, colspace[colspace_index].colspace );
718         bitmap[2] = new BBitmap( bitmapFrame, colspace[colspace_index].colspace );
719     }
720     // see if everything went well
721     status_t status = B_ERROR;
722     for (int32 i = 0; i < 3; i++)
723     {
724         if (bitmap[i])
725                 status = bitmap[i]->InitCheck();
726                 if (status < B_OK)
727                         break;
728     }
729     if (status >= B_OK)
730     {
731             // clear bitmaps to black
732             for (int32 i = 0; i < 3; i++)
733                 _BlankBitmap(bitmap[i]);
734     }
735     return status;
736 }
737
738 /*****************************************************************************
739  * VideoWindow::_FreeBuffers
740  *****************************************************************************/
741 void
742 VideoWindow::_FreeBuffers()
743 {
744         delete bitmap[0];
745         bitmap[0] = NULL;
746         delete bitmap[1];
747         bitmap[1] = NULL;
748         delete bitmap[2];
749         bitmap[2] = NULL;
750         fInitStatus = B_ERROR;
751 }
752
753 /*****************************************************************************
754  * VideoWindow::_BlankBitmap
755  *****************************************************************************/
756 void
757 VideoWindow::_BlankBitmap(BBitmap* bitmap) const
758 {
759         // no error checking (we do that earlier on and since it's a private function...
760
761         // YCbCr: 
762         // Loss/Saturation points are Y 16-235 (absoulte); Cb/Cr 16-240 (center 128)
763
764         // YUV: 
765         // Extrema points are Y 0 - 207 (absolute) U -91 - 91 (offset 128) V -127 - 127 (offset 128)
766
767         // we only handle weird colorspaces with special care
768         switch (bitmap->ColorSpace()) {
769                 case B_YCbCr422: {
770                         // Y0[7:0]  Cb0[7:0]  Y1[7:0]  Cr0[7:0]  Y2[7:0]  Cb2[7:0]  Y3[7:0]  Cr2[7:0]
771                         int32 height = bitmap->Bounds().IntegerHeight() + 1;
772                         uint8* bits = (uint8*)bitmap->Bits();
773                         int32 bpr = bitmap->BytesPerRow();
774                         for (int32 y = 0; y < height; y++) {
775                                 // handle 2 bytes at a time
776                                 for (int32 i = 0; i < bpr; i += 2) {
777                                         // offset into line
778                                         bits[i] = 16;
779                                         bits[i + 1] = 128;
780                                 }
781                                 // next line
782                                 bits += bpr;
783                         }
784                         break;
785                 }
786                 case B_YCbCr420: {
787 // TODO: untested!!
788                         // Non-interlaced only, Cb0  Y0  Y1  Cb2 Y2  Y3  on even scan lines ...
789                         // Cr0  Y0  Y1  Cr2 Y2  Y3  on odd scan lines
790                         int32 height = bitmap->Bounds().IntegerHeight() + 1;
791                         uint8* bits = (uint8*)bitmap->Bits();
792                         int32 bpr = bitmap->BytesPerRow();
793                         for (int32 y = 0; y < height; y += 1) {
794                                 // handle 3 bytes at a time
795                                 for (int32 i = 0; i < bpr; i += 3) {
796                                         // offset into line
797                                         bits[i] = 128;
798                                         bits[i + 1] = 16;
799                                         bits[i + 2] = 16;
800                                 }
801                                 // next line
802                                 bits += bpr;
803                         }
804                         break;
805                 }
806                 case B_YUV422: {
807 // TODO: untested!!
808                         // U0[7:0]  Y0[7:0]   V0[7:0]  Y1[7:0]  U2[7:0]  Y2[7:0]   V2[7:0]  Y3[7:0]
809                         int32 height = bitmap->Bounds().IntegerHeight() + 1;
810                         uint8* bits = (uint8*)bitmap->Bits();
811                         int32 bpr = bitmap->BytesPerRow();
812                         for (int32 y = 0; y < height; y += 1) {
813                                 // handle 2 bytes at a time
814                                 for (int32 i = 0; i < bpr; i += 2) {
815                                         // offset into line
816                                         bits[i] = 128;
817                                         bits[i + 1] = 0;
818                                 }
819                                 // next line
820                                 bits += bpr;
821                         }
822                         break;
823                 }
824                 default:
825                         memset(bitmap->Bits(), 0, bitmap->BitsLength());
826                         break;
827         }
828 }
829
830 /*****************************************************************************
831  * VideoWindow::_SetVideoSize
832  *****************************************************************************/
833 void
834 VideoWindow::_SetVideoSize(uint32 mode)
835 {
836         // let size depend on aspect correction
837         int32 width = CorrectAspectRatio() ? i_width : fTrueWidth;
838         int32 height = CorrectAspectRatio() ? i_height : fTrueHeight;
839         switch (mode)
840         {
841                 case RESIZE_50:
842                         width /= 2;
843                         height /= 2;
844                         break;
845                 case RESIZE_200:
846                         width *= 2;
847                         height *= 2;
848                         break;
849                 case RESIZE_100:
850                 default:
851                 break;
852         }
853         fSettings->ClearFlags(VideoSettings::FLAG_FULL_SCREEN);
854         ResizeTo(width, height);
855 }
856
857 /*****************************************************************************
858  * VideoWindow::_SetToSettings
859  *****************************************************************************/
860 void
861 VideoWindow::_SetToSettings()
862 {
863         // adjust dimensions
864         uint32 mode = RESIZE_100;
865         switch (fSettings->VideoSize())
866         {
867                 case VideoSettings::SIZE_50:
868                         mode = RESIZE_50;
869                         break;
870                 case VideoSettings::SIZE_200:
871                         mode = RESIZE_200;
872                         break;
873                 case VideoSettings::SIZE_100:
874                 case VideoSettings::SIZE_OTHER:
875                 default:
876                         break;
877         }
878         bool fullscreen = IsFullScreen();       // remember settings
879         _SetVideoSize(mode);                            // because this will reset settings
880         // the fullscreen status is reflected in the settings,
881         // but not yet in the windows state
882         if (fullscreen)
883                 SetFullScreen(true);
884         if (fSettings->HasFlags(VideoSettings::FLAG_ON_TOP_ALL))
885                 fCachedFeel = B_FLOATING_ALL_WINDOW_FEEL;
886         else
887                 fCachedFeel = B_NORMAL_WINDOW_FEEL;
888         SetFeel(fCachedFeel);
889 }
890
891 /*****************************************************************************
892  * VideoWindow::_SaveScreenShot
893  *****************************************************************************/
894 void
895 VideoWindow::_SaveScreenShot( BBitmap* bitmap, char* path,
896                                                   uint32 translatorID ) const
897 {
898         // make the info object from the parameters
899         screen_shot_info* info = new screen_shot_info;
900         info->bitmap = bitmap;
901         info->path = path;
902         info->translatorID = translatorID;
903         info->width = CorrectAspectRatio() ? i_width : fTrueWidth;
904         info->height = CorrectAspectRatio() ? i_height : fTrueHeight;
905         // spawn a new thread to take care of the actual saving to disk
906         thread_id thread = spawn_thread( _save_screen_shot,
907                                                                          "screen shot saver",
908                                                                          B_LOW_PRIORITY, (void*)info );
909         // start thread or do the job ourself if something went wrong
910         if ( thread < B_OK || resume_thread( thread ) < B_OK )
911                 _save_screen_shot( (void*)info );
912 }
913
914 /*****************************************************************************
915  * VideoWindow::_save_screen_shot
916  *****************************************************************************/
917 int32
918 VideoWindow::_save_screen_shot( void* cookie )
919 {
920         screen_shot_info* info = (screen_shot_info*)cookie;
921         if ( info && info->bitmap && info->bitmap->IsValid() && info->path )
922         {
923                 // try to be as quick as possible creating the file (the user might have
924                 // taken the next screen shot already!)
925                 // make sure we have a unique name for the screen shot
926                 BString path( info->path );
927                 // create the folder if it doesn't exist
928                 BString folder( info->path );
929                 create_directory( folder.String(), 0777 );
930                 path << "/vlc screenshot";
931                 BEntry entry( path.String() );
932                 int32 appendedNumber = 0;
933                 if ( entry.Exists() && !entry.IsSymLink() )
934                 {
935                         // we would clobber an existing entry
936                         bool foundUniqueName = false;
937                         appendedNumber = 1;
938                         while ( !foundUniqueName ) {
939                                 BString newName( path.String() );
940                                 newName << " " << appendedNumber;
941                                 BEntry possiblyClobberedEntry( newName.String() );
942                                 if ( possiblyClobberedEntry.Exists()
943                                         && !possiblyClobberedEntry.IsSymLink() )
944                                         appendedNumber++;
945                                 else
946                                         foundUniqueName = true;
947                         }
948                 }
949                 if ( appendedNumber > 0 )
950                         path << " " << appendedNumber;
951                 // there is still a slight chance to clobber an existing
952                 // file (if it was created in the "meantime"), but we take it...
953                 BFile outFile( path.String(),
954                                            B_CREATE_FILE | B_WRITE_ONLY | B_ERASE_FILE );
955
956                 // make colorspace converted copy of bitmap
957                 BBitmap* converted = new BBitmap( BRect( 0.0, 0.0, info->width, info->height ),
958                                                                                   B_RGB32 );
959                 status_t status = convert_bitmap( info->bitmap, converted );
960                 if ( status == B_OK )
961                 {
962                         BTranslatorRoster* roster = BTranslatorRoster::Default();
963                         uint32 imageFormat = 0;
964                         translator_id translator = 0;
965                         bool found = false;
966
967                         // find suitable translator
968                         translator_id* ids = NULL;
969                         int32 count = 0;
970                 
971                         status = roster->GetAllTranslators( &ids, &count );
972                         if ( status >= B_OK )
973                         {
974                                 for ( int tix = 0; tix < count; tix++ )
975                                 { 
976                                         const translation_format *formats = NULL; 
977                                         int32 num_formats = 0; 
978                                         bool ok = false; 
979                                         status = roster->GetInputFormats( ids[tix],
980                                                                                                           &formats, &num_formats );
981                                         if (status >= B_OK)
982                                         {
983                                                 for ( int iix = 0; iix < num_formats; iix++ )
984                                                 { 
985                                                         if ( formats[iix].type == B_TRANSLATOR_BITMAP )
986                                                         { 
987                                                                 ok = true; 
988                                                                 break; 
989                                                         }
990                                                 }
991                                         }
992                                         if ( !ok )
993                                                 continue; 
994                                         status = roster->GetOutputFormats( ids[tix],
995                                                                                                            &formats, &num_formats); 
996                                         if ( status >= B_OK )
997                                         {
998                                                 for ( int32 oix = 0; oix < num_formats; oix++ )
999                                                 {
1000                                                         if ( formats[oix].type != B_TRANSLATOR_BITMAP )
1001                                                         {
1002                                                                 if ( formats[oix].type == info->translatorID )
1003                                                                 {
1004                                                                         found = true;
1005                                                                         imageFormat = formats[oix].type;
1006                                                                         translator = ids[tix];
1007                                                                         break;
1008                                                                 }
1009                                                         }
1010                                                 }
1011                                         }
1012                                 }
1013                         }
1014                         delete[] ids;
1015                         if ( found )
1016                         {
1017                                 // make bitmap stream
1018                                 BBitmapStream outStream( converted );
1019
1020                                 status = outFile.InitCheck();
1021                                 if (status == B_OK) {
1022                                         status = roster->Translate( &outStream, NULL, NULL,
1023                                                                                                 &outFile, imageFormat );
1024                                         if ( status == B_OK )
1025                                         {
1026                                                 BNodeInfo nodeInfo( &outFile );
1027                                                 if ( nodeInfo.InitCheck() == B_OK )
1028                                                 {
1029                                                         translation_format* formats; 
1030                                                         int32 count;
1031                                                         status = roster->GetOutputFormats( translator,
1032                                                                                                                            (const translation_format **) &formats,
1033                                                                                                                            &count);
1034                                                         if ( status >= B_OK )
1035                                                         {
1036                                                                 const char * mime = NULL; 
1037                                                                 for ( int ix = 0; ix < count; ix++ ) {
1038                                                                         if ( formats[ix].type == imageFormat ) {
1039                                                                                 mime = formats[ix].MIME;
1040                                                                                 break;
1041                                                                         }
1042                                                                 } 
1043                                                                 if ( mime )
1044                                                                         nodeInfo.SetType( mime );
1045                                                         }
1046                                                 }
1047                                         }
1048                                 }
1049                                 outStream.DetachBitmap( &converted );
1050                                 outFile.Unset();
1051                         }
1052                 }
1053                 delete converted;
1054         }
1055         if ( info )
1056         {
1057                 delete info->bitmap;
1058                 free( info->path );
1059         }
1060         delete info;
1061         return B_OK;
1062 }
1063
1064
1065 /*****************************************************************************
1066  * VLCView::VLCView
1067  *****************************************************************************/
1068 VLCView::VLCView(BRect bounds, vout_thread_t *p_vout_instance )
1069         : BView(bounds, "video view", B_FOLLOW_NONE, B_WILL_DRAW | B_PULSE_NEEDED),
1070           fLastMouseMovedTime(system_time()),
1071           fCursorHidden(false),
1072           fCursorInside(false),
1073           fIgnoreDoubleClick(false)
1074 {
1075     p_vout = p_vout_instance;
1076     SetViewColor(B_TRANSPARENT_32_BIT);
1077 }
1078
1079 /*****************************************************************************
1080  * VLCView::~VLCView
1081  *****************************************************************************/
1082 VLCView::~VLCView()
1083 {
1084 }
1085
1086 /*****************************************************************************
1087  * VLCVIew::AttachedToWindow
1088  *****************************************************************************/
1089 void
1090 VLCView::AttachedToWindow()
1091 {
1092         // in order to get keyboard events
1093         MakeFocus(true);
1094         // periodically check if we want to hide the pointer
1095         Window()->SetPulseRate(1000000);
1096 }
1097
1098 /*****************************************************************************
1099  * VLCVIew::MouseDown
1100  *****************************************************************************/
1101 void
1102 VLCView::MouseDown(BPoint where)
1103 {
1104         VideoWindow* videoWindow = dynamic_cast<VideoWindow*>(Window());
1105         BMessage* msg = Window()->CurrentMessage();
1106         int32 clicks;
1107         uint32 buttons;
1108         msg->FindInt32("clicks", &clicks);
1109         msg->FindInt32("buttons", (int32*)&buttons);
1110
1111         if (videoWindow)
1112         {
1113                 if (buttons & B_PRIMARY_MOUSE_BUTTON)
1114                 {
1115                         if (clicks == 2 && !fIgnoreDoubleClick)
1116                                 Window()->Zoom();
1117                         /* else
1118                                 videoWindow->ToggleInterfaceShowing(); */
1119                         fIgnoreDoubleClick = false;
1120                 }
1121             else
1122             {
1123                         if (buttons & B_SECONDARY_MOUSE_BUTTON) 
1124                         {
1125                                 // clicks will be 2 next time (if interval short enough)
1126                                 // even if the first click and the second
1127                                 // have not been made with the same mouse button
1128                                 fIgnoreDoubleClick = true;
1129                                 // launch popup menu
1130                                 BPopUpMenu *menu = new BPopUpMenu("context menu");
1131                                 menu->SetRadioMode(false);
1132                                 // In full screen, add an item to show/hide the interface
1133                                 if( videoWindow->IsFullScreen() )
1134                                 {
1135                                     BMenuItem *intfItem =
1136                                         new BMenuItem( _("Show Interface"), new BMessage(SHOW_INTERFACE) );
1137                                     menu->AddItem( intfItem );
1138                                 }
1139                                 // Resize to 50%
1140                                 BMenuItem *halfItem = new BMenuItem(_("50%"), new BMessage(RESIZE_50));
1141                                 menu->AddItem(halfItem);
1142                                 // Resize to 100%
1143                                 BMenuItem *origItem = new BMenuItem(_("100%"), new BMessage(RESIZE_100));
1144                                 menu->AddItem(origItem);
1145                                 // Resize to 200%
1146                                 BMenuItem *doubleItem = new BMenuItem(_("200%"), new BMessage(RESIZE_200));
1147                                 menu->AddItem(doubleItem);
1148                                 // Toggle FullScreen
1149                                 BMenuItem *zoomItem = new BMenuItem(_("Fullscreen"), new BMessage(TOGGLE_FULL_SCREEN));
1150                                 zoomItem->SetMarked(videoWindow->IsFullScreen());
1151                                 menu->AddItem(zoomItem);
1152         
1153                                 menu->AddSeparatorItem();
1154         
1155                                 // Toggle vSync
1156                                 BMenuItem *vsyncItem = new BMenuItem(_("Vertical Sync"), new BMessage(VERT_SYNC));
1157                                 vsyncItem->SetMarked(videoWindow->IsSyncedToRetrace());
1158                                 menu->AddItem(vsyncItem);
1159                                 // Correct Aspect Ratio
1160                                 BMenuItem *aspectItem = new BMenuItem(_("Correct Aspect Ratio"), new BMessage(ASPECT_CORRECT));
1161                                 aspectItem->SetMarked(videoWindow->CorrectAspectRatio());
1162                                 menu->AddItem(aspectItem);
1163         
1164                                 menu->AddSeparatorItem();
1165         
1166                                 // Windwo Feel Items
1167 /*                              BMessage *winNormFeel = new BMessage(WINDOW_FEEL);
1168                                 winNormFeel->AddInt32("WinFeel", (int32)B_NORMAL_WINDOW_FEEL);
1169                                 BMenuItem *normWindItem = new BMenuItem("Normal Window", winNormFeel);
1170                                 normWindItem->SetMarked(videoWindow->Feel() == B_NORMAL_WINDOW_FEEL);
1171                                 menu->AddItem(normWindItem);
1172                                 
1173                                 BMessage *winFloatFeel = new BMessage(WINDOW_FEEL);
1174                                 winFloatFeel->AddInt32("WinFeel", (int32)B_FLOATING_APP_WINDOW_FEEL);
1175                                 BMenuItem *onTopWindItem = new BMenuItem("App Top", winFloatFeel);
1176                                 onTopWindItem->SetMarked(videoWindow->Feel() == B_FLOATING_APP_WINDOW_FEEL);
1177                                 menu->AddItem(onTopWindItem);
1178                                 
1179                                 BMessage *winAllFeel = new BMessage(WINDOW_FEEL);
1180                                 winAllFeel->AddInt32("WinFeel", (int32)B_FLOATING_ALL_WINDOW_FEEL);
1181                                 BMenuItem *allSpacesWindItem = new BMenuItem("On Top All Workspaces", winAllFeel);
1182                                 allSpacesWindItem->SetMarked(videoWindow->Feel() == B_FLOATING_ALL_WINDOW_FEEL);
1183                                 menu->AddItem(allSpacesWindItem);*/
1184
1185                                 BMessage *windowFeelMsg = new BMessage( WINDOW_FEEL );
1186                                 bool onTop = videoWindow->Feel() == B_FLOATING_ALL_WINDOW_FEEL;
1187                                 window_feel feel = onTop ? B_NORMAL_WINDOW_FEEL : B_FLOATING_ALL_WINDOW_FEEL;
1188                                 windowFeelMsg->AddInt32( "WinFeel", (int32)feel );
1189                                 BMenuItem *windowFeelItem = new BMenuItem( _("Stay On Top"), windowFeelMsg );
1190                                 windowFeelItem->SetMarked( onTop );
1191                                 menu->AddItem( windowFeelItem );
1192
1193                                 menu->AddSeparatorItem();
1194
1195                                 BMenuItem* screenShotItem = new BMenuItem( _("Take Screen Shot"),
1196                                                                                                                    new BMessage( SCREEN_SHOT ) );
1197                                 menu->AddItem( screenShotItem );
1198
1199                                 menu->SetTargetForItems( this );
1200                                 ConvertToScreen( &where );
1201                                 menu->Go( where, true, false, true );
1202                 }
1203                 }
1204         }
1205         fLastMouseMovedTime = system_time();
1206         fCursorHidden = false;
1207 }
1208
1209 /*****************************************************************************
1210  * VLCVIew::MouseUp
1211  *****************************************************************************/
1212 void
1213 VLCView::MouseUp( BPoint where )
1214 {
1215     vlc_value_t val;
1216     val.b_bool = VLC_TRUE;
1217     var_Set( p_vout, "mouse-clicked", val );
1218 }
1219
1220 /*****************************************************************************
1221  * VLCVIew::MouseMoved
1222  *****************************************************************************/
1223 void
1224 VLCView::MouseMoved(BPoint point, uint32 transit, const BMessage* dragMessage)
1225 {
1226         fLastMouseMovedTime = system_time();
1227         fCursorHidden = false;
1228         fCursorInside = (transit == B_INSIDE_VIEW || transit == B_ENTERED_VIEW);
1229         /* DVD navigation */
1230         unsigned int i_width, i_height, i_x, i_y;
1231     vout_PlacePicture( p_vout, (unsigned int)Bounds().Width(),
1232                        (unsigned int)Bounds().Height(),
1233                        &i_x, &i_y, &i_width, &i_height );
1234         vlc_value_t val;
1235         val.i_int = ( (int)point.x - i_x ) * p_vout->render.i_width / i_width;
1236         var_Set( p_vout, "mouse-x", val );
1237         val.i_int = ( (int)point.y - i_y ) * p_vout->render.i_height / i_height;
1238         var_Set( p_vout, "mouse-y", val );
1239         val.b_bool = VLC_TRUE;
1240     var_Set( p_vout, "mouse-moved", val );
1241 }
1242
1243 /*****************************************************************************
1244  * VLCVIew::Pulse
1245  *****************************************************************************/
1246 void 
1247 VLCView::Pulse()
1248 {
1249         // We are getting the pulse messages no matter if the mouse is over
1250         // this view. If we are in full screen mode, we want to hide the cursor
1251         // even if it is not.
1252         VideoWindow *videoWindow = dynamic_cast<VideoWindow*>(Window());
1253         if (!fCursorHidden)
1254         {
1255                 if (fCursorInside
1256                         && system_time() - fLastMouseMovedTime > MOUSE_IDLE_TIMEOUT)
1257                 {
1258                         be_app->ObscureCursor();
1259                         fCursorHidden = true;
1260                         
1261                         // hide the interface window as well if full screen
1262                         if (videoWindow && videoWindow->IsFullScreen())
1263                                 videoWindow->SetInterfaceShowing(false);
1264                 }
1265         }
1266
1267     // Workaround to disable the screensaver in full screen:
1268     // we simulate an activity every 29 seconds 
1269         if( videoWindow && videoWindow->IsFullScreen() &&
1270             system_time() - fLastMouseMovedTime > 29000000 )
1271         {
1272             BPoint where;
1273                 uint32 buttons;
1274                 GetMouse(&where, &buttons, false);
1275                 ConvertToScreen(&where);
1276                 set_mouse_position((int32) where.x, (int32) where.y);
1277         }
1278 }
1279
1280 /*****************************************************************************
1281  * VLCVIew::KeyDown
1282  *****************************************************************************/
1283 void
1284 VLCView::KeyDown(const char *bytes, int32 numBytes)
1285 {
1286     VideoWindow *videoWindow = dynamic_cast<VideoWindow*>(Window());
1287     BWindow* interfaceWindow = get_interface_window();
1288         if (videoWindow && numBytes > 0) {
1289                 uint32 mods = modifiers();
1290                 switch (*bytes) {
1291                         case B_TAB:
1292                         case 'f':
1293                         case 'F':
1294                                 // toggle window and full screen mode
1295                                 // not passing on the tab key to the default KeyDown()
1296                                 // implementation also avoids loosing the keyboard focus
1297                                 videoWindow->PostMessage(TOGGLE_FULL_SCREEN);
1298                                 break;
1299                         case B_ESCAPE:
1300                                 // go back to window mode
1301                                 if (videoWindow->IsFullScreen())
1302                                         videoWindow->PostMessage(TOGGLE_FULL_SCREEN);
1303                                 break;
1304                         case B_SPACE:
1305                                 // toggle playback
1306                                 if (interfaceWindow)
1307                                         interfaceWindow->PostMessage(PAUSE_PLAYBACK);
1308                                 break;
1309                         case B_RIGHT_ARROW:
1310                                 if (interfaceWindow)
1311                                 {
1312                                         if (mods & B_SHIFT_KEY)
1313                                                 // next title
1314                                                 interfaceWindow->PostMessage(NEXT_TITLE);
1315                                         else
1316                                                 // next chapter
1317                                                 interfaceWindow->PostMessage(NEXT_CHAPTER);
1318                                 }
1319                                 break;
1320                         case B_LEFT_ARROW:
1321                                 if (interfaceWindow)
1322                                 {
1323                                         if (mods & B_SHIFT_KEY)
1324                                                 // previous title
1325                                                 interfaceWindow->PostMessage(PREV_TITLE);
1326                                         else
1327                                                 // previous chapter
1328                                                 interfaceWindow->PostMessage(PREV_CHAPTER);
1329                                 }
1330                                 break;
1331                         case B_UP_ARROW:
1332                                 // previous file in playlist
1333                                 interfaceWindow->PostMessage(PREV_FILE);
1334                                 break;
1335                         case B_DOWN_ARROW:
1336                                 // next file in playlist
1337                                 interfaceWindow->PostMessage(NEXT_FILE);
1338                                 break;
1339                         case B_PRINT_KEY:
1340                         case 's':
1341                         case 'S':
1342                                 videoWindow->PostMessage( SCREEN_SHOT );
1343                                 break;
1344                         default:
1345                                 BView::KeyDown(bytes, numBytes);
1346                                 break;
1347                 }
1348         }
1349 }
1350
1351 /*****************************************************************************
1352  * VLCVIew::Draw
1353  *****************************************************************************/
1354 void
1355 VLCView::Draw(BRect updateRect) 
1356 {
1357         VideoWindow* window = dynamic_cast<VideoWindow*>( Window() );
1358         if ( window && window->mode == BITMAP )
1359                 FillRect( updateRect );
1360 }
1361
1362 /*****************************************************************************
1363  * Local prototypes
1364  *****************************************************************************/
1365 static int  Init       ( vout_thread_t * );
1366 static void End        ( vout_thread_t * );
1367 // static int  Manage     ( vout_thread_t * );
1368 static void Display    ( vout_thread_t *, picture_t * );
1369
1370 static int  BeosOpenDisplay ( vout_thread_t *p_vout );
1371 static void BeosCloseDisplay( vout_thread_t *p_vout );
1372
1373 /*****************************************************************************
1374  * OpenVideo: allocates BeOS video thread output method
1375  *****************************************************************************
1376  * This function allocates and initializes a BeOS vout method.
1377  *****************************************************************************/
1378 int E_(OpenVideo) ( vlc_object_t *p_this )
1379 {
1380     vout_thread_t * p_vout = (vout_thread_t *)p_this;
1381
1382     /* Allocate structure */
1383     p_vout->p_sys = (vout_sys_t*) malloc( sizeof( vout_sys_t ) );
1384     if( p_vout->p_sys == NULL )
1385     {
1386         msg_Err( p_vout, "out of memory" );
1387         return( 1 );
1388     }
1389     p_vout->p_sys->i_width = p_vout->render.i_width;
1390     p_vout->p_sys->i_height = p_vout->render.i_height;
1391     p_vout->p_sys->source_chroma = p_vout->render.i_chroma;
1392
1393     p_vout->pf_init = Init;
1394     p_vout->pf_end = End;
1395     p_vout->pf_manage = NULL;
1396     p_vout->pf_render = NULL;
1397     p_vout->pf_display = Display;
1398
1399     return( 0 );
1400 }
1401
1402 /*****************************************************************************
1403  * Init: initialize BeOS video thread output method
1404  *****************************************************************************/
1405 int Init( vout_thread_t *p_vout )
1406 {
1407     int i_index;
1408     picture_t *p_pic;
1409
1410     I_OUTPUTPICTURES = 0;
1411
1412     /* Open and initialize device */
1413     if( BeosOpenDisplay( p_vout ) )
1414     {
1415         msg_Err(p_vout, "vout error: can't open display");
1416         return 0;
1417     }
1418     p_vout->output.i_width  = p_vout->render.i_width;
1419     p_vout->output.i_height = p_vout->render.i_height;
1420
1421     /* Assume we have square pixels */
1422     p_vout->output.i_aspect = p_vout->p_sys->i_width
1423                                * VOUT_ASPECT_FACTOR / p_vout->p_sys->i_height;
1424     p_vout->output.i_chroma = colspace[p_vout->p_sys->p_window->colspace_index].chroma;
1425     p_vout->p_sys->i_index = 0;
1426
1427     p_vout->b_direct = 1;
1428
1429     p_vout->output.i_rmask  = 0x00ff0000;
1430     p_vout->output.i_gmask  = 0x0000ff00;
1431     p_vout->output.i_bmask  = 0x000000ff;
1432
1433     for (int buffer_index = 0 ; buffer_index < 3; buffer_index++)
1434     {
1435        p_pic = NULL;
1436        /* Find an empty picture slot */
1437        for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
1438        {
1439            p_pic = NULL;
1440            if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
1441            {
1442                p_pic = p_vout->p_picture + i_index;
1443                break;
1444            }
1445        }
1446
1447        if( p_pic == NULL )
1448        {
1449            return 0;
1450        }
1451        p_pic->p->p_pixels = (u8*)p_vout->p_sys->p_window->bitmap[buffer_index]->Bits();
1452        p_pic->p->i_lines = p_vout->p_sys->i_height;
1453
1454        p_pic->p->i_pixel_pitch = colspace[p_vout->p_sys->p_window->colspace_index].pixel_bytes;
1455        p_pic->i_planes = colspace[p_vout->p_sys->p_window->colspace_index].planes;
1456        p_pic->p->i_pitch = p_vout->p_sys->p_window->bitmap[buffer_index]->BytesPerRow(); 
1457        p_pic->p->i_visible_pitch = p_pic->p->i_pixel_pitch * ( p_vout->p_sys->p_window->bitmap[buffer_index]->Bounds().IntegerWidth() + 1 );
1458
1459        p_pic->i_status = DESTROYED_PICTURE;
1460        p_pic->i_type   = DIRECT_PICTURE;
1461  
1462        PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
1463
1464        I_OUTPUTPICTURES++;
1465     }
1466
1467     return( 0 );
1468 }
1469
1470 /*****************************************************************************
1471  * End: terminate BeOS video thread output method
1472  *****************************************************************************/
1473 void End( vout_thread_t *p_vout )
1474 {
1475     BeosCloseDisplay( p_vout );
1476 }
1477
1478 /*****************************************************************************
1479  * CloseVideo: destroy BeOS video thread output method
1480  *****************************************************************************
1481  * Terminate an output method created by DummyCreateOutputMethod
1482  *****************************************************************************/
1483 void E_(CloseVideo) ( vlc_object_t *p_this )
1484 {
1485     vout_thread_t * p_vout = (vout_thread_t *)p_this;
1486
1487     free( p_vout->p_sys );
1488 }
1489
1490 /*****************************************************************************
1491  * Display: displays previously rendered output
1492  *****************************************************************************
1493  * This function send the currently rendered image to BeOS image, waits until
1494  * it is displayed and switch the two rendering buffers, preparing next frame.
1495  *****************************************************************************/
1496 void Display( vout_thread_t *p_vout, picture_t *p_pic )
1497 {
1498     VideoWindow * p_win = p_vout->p_sys->p_window;
1499
1500     /* draw buffer if required */    
1501     if (!p_win->teardownwindow)
1502     { 
1503        p_win->drawBuffer(p_vout->p_sys->i_index);
1504     }
1505     /* change buffer */
1506     p_vout->p_sys->i_index = ++p_vout->p_sys->i_index % 3;
1507     p_pic->p->p_pixels = (u8*)p_vout->p_sys->p_window->bitmap[p_vout->p_sys->i_index]->Bits();
1508 }
1509
1510 /* following functions are local */
1511
1512 /*****************************************************************************
1513  * BeosOpenDisplay: open and initialize BeOS device
1514  *****************************************************************************/
1515 static int BeosOpenDisplay( vout_thread_t *p_vout )
1516
1517
1518     p_vout->p_sys->p_window = new VideoWindow( p_vout->p_sys->i_width - 1,
1519                                                p_vout->p_sys->i_height - 1,
1520                                                BRect( 20, 50,
1521                                                       20 + p_vout->i_window_width - 1, 
1522                                                       50 + p_vout->i_window_height - 1 ),
1523                                                p_vout );
1524     if( p_vout->p_sys->p_window == NULL )
1525     {
1526         msg_Err( p_vout, "cannot allocate VideoWindow" );
1527         return( 1 );
1528     }
1529     else
1530     {
1531         p_vout->p_sys->p_window->Show();
1532     }
1533     
1534     return( 0 );
1535 }
1536
1537 /*****************************************************************************
1538  * BeosDisplay: close and reset BeOS device
1539  *****************************************************************************
1540  * Returns all resources allocated by BeosOpenDisplay and restore the original
1541  * state of the device.
1542  *****************************************************************************/
1543 static void BeosCloseDisplay( vout_thread_t *p_vout )
1544 {    
1545     VideoWindow * p_win = p_vout->p_sys->p_window;
1546     /* Destroy the video window */
1547     if( p_win != NULL && !p_win->teardownwindow)
1548     {
1549         p_win->Lock();
1550         p_win->teardownwindow = true;
1551         p_win->Hide();
1552         p_win->Quit();
1553     }
1554     p_win = NULL;
1555 }