]> git.saurik.com Git - wxWidgets.git/blob - src/mac/carbon/mediactrl.cpp
9a6a0f075cf36ac8a33fc2257c4e193b723c1c88
[wxWidgets.git] / src / mac / carbon / mediactrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: mac/carbon/mediactrl.cpp
3 // Purpose: Built-in Media Backends for Mac
4 // Author: Ryan Norton <wxprojects@comcast.net>
5 // Modified by:
6 // Created: 11/07/04
7 // RCS-ID: $Id$
8 // Copyright: (c) 2004-2006 Ryan Norton
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
13 // OK, a casual overseer of this file may wonder why we don't use
14 // either CreateMovieControl or HIMovieView...
15 //
16 // CreateMovieControl
17 // 1) Need to dispose and create each time a new movie is loaded
18 // 2) Not that many real advantages
19 // 3) Progressively buggier in higher OSX versions
20 // (see main.c of QTCarbonShell sample for details)
21 // HIMovieView
22 // 1) Crashes on destruction in ALL cases on quite a few systems!
23 // (With the only real "alternative" is to simply not
24 // dispose of it and let it leak...)
25 // 2) Massive refreshing bugs with its movie controller between
26 // movies
27 //
28 // At one point we had a complete implementation for CreateMovieControl
29 // and on my (RN) local copy I had one for HIMovieView - but they
30 // were simply deemed to be too buggy/unuseful. HIMovieView could
31 // have been useful as well because it uses OpenGL contexts instead
32 // of GWorlds. Perhaps someday when someone comes out with some
33 // ingenious workarounds :).
34 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35
36 // For compilers that support precompilation, includes "wx.h".
37 #include "wx/wxprec.h"
38
39 #include "wx/mediactrl.h"
40
41 // uma is for wxMacFSSpec
42 #include "wx/mac/uma.h"
43 #include "wx/timer.h"
44 #include "wx/log.h"
45
46 // standard QT stuff
47 #ifndef __DARWIN__
48 #include <Movies.h>
49 #include <Gestalt.h>
50 #include <QuickTimeComponents.h>
51 #else
52 #include <QuickTime/QuickTimeComponents.h>
53 #endif
54
55 #if wxUSE_MEDIACTRL
56
57 //---------------------------------------------------------------------------
58 // Height and Width of movie controller in the movie control (apple samples)
59 //---------------------------------------------------------------------------
60 #define wxMCWIDTH 320
61 #define wxMCHEIGHT 16
62
63 //===========================================================================
64 // BACKEND DECLARATIONS
65 //===========================================================================
66
67 //---------------------------------------------------------------------------
68 // wxQTMediaBackend
69 //---------------------------------------------------------------------------
70
71 class WXDLLIMPEXP_MEDIA wxQTMediaBackend : public wxMediaBackendCommonBase
72 {
73 public:
74 wxQTMediaBackend();
75 ~wxQTMediaBackend();
76
77 virtual bool CreateControl(wxControl* ctrl, wxWindow* parent,
78 wxWindowID id,
79 const wxPoint& pos,
80 const wxSize& size,
81 long style,
82 const wxValidator& validator,
83 const wxString& name);
84
85 virtual bool Load(const wxString& fileName);
86 virtual bool Load(const wxURI& location);
87
88 virtual bool Play();
89 virtual bool Pause();
90 virtual bool Stop();
91
92 virtual wxMediaState GetState();
93
94 virtual bool SetPosition(wxLongLong where);
95 virtual wxLongLong GetPosition();
96 virtual wxLongLong GetDuration();
97
98 virtual void Move(int x, int y, int w, int h);
99 wxSize GetVideoSize() const;
100
101 virtual double GetPlaybackRate();
102 virtual bool SetPlaybackRate(double dRate);
103
104 virtual double GetVolume();
105 virtual bool SetVolume(double);
106
107 void Cleanup();
108 void FinishLoad();
109
110 virtual bool ShowPlayerControls(wxMediaCtrlPlayerControls flags);
111
112 virtual wxLongLong GetDownloadProgress();
113 virtual wxLongLong GetDownloadTotal();
114
115 virtual void MacVisibilityChanged();
116
117 //
118 // ------ Implementation from now on --------
119 //
120 bool DoPause();
121 bool DoStop();
122
123 void DoLoadBestSize();
124 void DoSetControllerVisible(wxMediaCtrlPlayerControls flags);
125
126 wxLongLong GetDataSizeFromStart(TimeValue end);
127
128 Boolean IsQuickTime4Installed();
129 void DoNewMovieController();
130
131 static pascal void PPRMProc(
132 Movie theMovie, OSErr theErr, void* theRefCon);
133
134 //TODO: Last param actually long - does this work on 64bit machines?
135 static pascal Boolean MCFilterProc(MovieController theController,
136 short action, void *params, long refCon);
137
138 static pascal OSStatus WindowEventHandler(
139 EventHandlerCallRef inHandlerCallRef,
140 EventRef inEvent, void *inUserData );
141
142 wxSize m_bestSize; // Original movie size
143 Movie m_movie; // Movie instance
144 bool m_bPlaying; // Whether media is playing or not
145 class wxTimer* m_timer; // Timer for streaming the movie
146 MovieController m_mc; // MovieController instance
147 wxMediaCtrlPlayerControls m_interfaceflags; // Saved interface flags
148
149 // Event handlers and UPPs/Callbacks
150 EventHandlerRef m_windowEventHandler;
151 EventHandlerUPP m_windowUPP;
152
153 MoviePrePrerollCompleteUPP m_preprerollupp;
154 MCActionFilterWithRefConUPP m_mcactionupp;
155
156 GWorldPtr m_movieWorld; //Offscreen movie GWorld
157
158 friend class wxQTMediaEvtHandler;
159
160 DECLARE_DYNAMIC_CLASS(wxQTMediaBackend)
161 };
162
163 // helper to hijack background erasing for the QT window
164 class WXDLLIMPEXP_MEDIA wxQTMediaEvtHandler : public wxEvtHandler
165 {
166 public:
167 wxQTMediaEvtHandler(wxQTMediaBackend *qtb)
168 {
169 m_qtb = qtb;
170
171 qtb->m_ctrl->Connect(
172 qtb->m_ctrl->GetId(), wxEVT_ERASE_BACKGROUND,
173 wxEraseEventHandler(wxQTMediaEvtHandler::OnEraseBackground),
174 NULL, this);
175 }
176
177 void OnEraseBackground(wxEraseEvent& event);
178
179 private:
180 wxQTMediaBackend *m_qtb;
181
182 DECLARE_NO_COPY_CLASS(wxQTMediaEvtHandler)
183 };
184
185 //===========================================================================
186 // IMPLEMENTATION
187 //===========================================================================
188
189
190 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
191 //
192 // wxQTMediaBackend
193 //
194 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
195
196 IMPLEMENT_DYNAMIC_CLASS(wxQTMediaBackend, wxMediaBackend)
197
198 //Time between timer calls - this is the Apple recommondation to the TCL
199 //team I believe
200 #define MOVIE_DELAY 20
201
202 //---------------------------------------------------------------------------
203 // wxQTMediaLoadTimer
204 //
205 // QT, esp. QT for Windows is very picky about how you go about
206 // async loading. If you were to go through a Windows message loop
207 // or a MoviesTask or both and then check the movie load state
208 // it would still return 1000 (loading)... even (pre)prerolling doesn't
209 // help. However, making a load timer like this works
210 //---------------------------------------------------------------------------
211 class wxQTMediaLoadTimer : public wxTimer
212 {
213 public:
214 wxQTMediaLoadTimer(wxQTMediaBackend* parent) :
215 m_parent(parent) {}
216
217 void Notify()
218 {
219 ::MCIdle(m_parent->m_mc);
220
221 // kMovieLoadStatePlayable is not enough on MAC:
222 // it plays, but IsMovieDone might return true (!)
223 // sure we need to wait until kMovieLoadStatePlaythroughOK
224 if (::GetMovieLoadState(m_parent->m_movie) >= 20000)
225 {
226 m_parent->FinishLoad();
227 delete this;
228 }
229 }
230
231 protected:
232 wxQTMediaBackend *m_parent; // Backend pointer
233 };
234
235 // --------------------------------------------------------------------------
236 // wxQTMediaPlayTimer - Handle Asyncronous Playing
237 //
238 // 1) Checks to see if the movie is done, and if not continues
239 // streaming the movie
240 // 2) Sends the wxEVT_MEDIA_STOP event if we have reached the end of
241 // the movie.
242 // --------------------------------------------------------------------------
243 class wxQTMediaPlayTimer : public wxTimer
244 {
245 public:
246 wxQTMediaPlayTimer(wxQTMediaBackend* parent) :
247 m_parent(parent) {}
248
249 void Notify()
250 {
251 //
252 // OK, a little explaining - basically originally
253 // we only called MoviesTask if the movie was actually
254 // playing (not paused or stopped)... this was before
255 // we realized MoviesTask actually handles repainting
256 // of the current frame - so if you were to resize
257 // or something it would previously not redraw that
258 // portion of the movie.
259 //
260 // So now we call MoviesTask always so that it repaints
261 // correctly.
262 //
263 ::MCIdle(m_parent->m_mc);
264
265 //
266 // Handle the stop event - if the movie has reached
267 // the end, notify our handler
268 //
269 if (::IsMovieDone(m_parent->m_movie))
270 {
271 if ( m_parent->SendStopEvent() )
272 {
273 m_parent->Stop();
274 wxASSERT(::GetMoviesError() == noErr);
275
276 m_parent->QueueFinishEvent();
277 }
278 }
279 }
280
281 protected:
282 wxQTMediaBackend* m_parent; // Backend pointer
283 };
284
285
286 //---------------------------------------------------------------------------
287 // wxQTMediaBackend Constructor
288 //
289 // Sets m_timer to NULL signifying we havn't loaded anything yet
290 //---------------------------------------------------------------------------
291 wxQTMediaBackend::wxQTMediaBackend()
292 : m_movie(NULL), m_bPlaying(false), m_timer(NULL)
293 , m_mc(NULL), m_interfaceflags(wxMEDIACTRLPLAYERCONTROLS_NONE)
294 , m_preprerollupp(NULL), m_movieWorld(NULL)
295 {
296 }
297
298 //---------------------------------------------------------------------------
299 // wxQTMediaBackend Destructor
300 //
301 // 1) Cleans up the QuickTime movie instance
302 // 2) Decrements the QuickTime reference counter - if this reaches
303 // 0, QuickTime shuts down
304 // 3) Decrements the QuickTime Windows Media Layer reference counter -
305 // if this reaches 0, QuickTime shuts down the Windows Media Layer
306 //---------------------------------------------------------------------------
307 wxQTMediaBackend::~wxQTMediaBackend()
308 {
309 if (m_movie)
310 Cleanup();
311
312 // Cleanup for moviecontroller
313 if (m_mc)
314 {
315 // destroy wxQTMediaEvtHandler we pushed on it
316 m_ctrl->PopEventHandler(true);
317 RemoveEventHandler(m_windowEventHandler);
318 DisposeEventHandlerUPP(m_windowUPP);
319
320 // Dispose of the movie controller
321 ::DisposeMovieController(m_mc);
322 m_mc = NULL;
323 DisposeMCActionFilterWithRefConUPP(m_mcactionupp);
324
325 // Dispose of offscreen GWorld
326 ::DisposeGWorld(m_movieWorld);
327 }
328
329 // Note that ExitMovies() is not necessary...
330 ExitMovies();
331 }
332
333 //---------------------------------------------------------------------------
334 // wxQTMediaBackend::CreateControl
335 //
336 // 1) Intializes QuickTime
337 // 2) Creates the control window
338 //---------------------------------------------------------------------------
339 bool wxQTMediaBackend::CreateControl(
340 wxControl* ctrl,
341 wxWindow* parent,
342 wxWindowID id,
343 const wxPoint& pos,
344 const wxSize& size,
345 long style,
346 const wxValidator& validator,
347 const wxString& name)
348 {
349 if (!IsQuickTime4Installed())
350 return false;
351
352 EnterMovies();
353
354 wxMediaCtrl* mediactrl = (wxMediaCtrl*)ctrl;
355
356 //
357 // Create window
358 // By default wxWindow(s) is created with a border -
359 // so we need to get rid of those
360 //
361 // Since we don't have a child window like most other
362 // backends, we don't need wxCLIP_CHILDREN
363 //
364 if ( !mediactrl->wxControl::Create(
365 parent, id, pos, size,
366 wxWindow::MacRemoveBordersFromStyle(style),
367 validator, name))
368 {
369 return false;
370 }
371
372 #if wxUSE_VALIDATORS
373 mediactrl->SetValidator(validator);
374 #endif
375
376 m_ctrl = mediactrl;
377 return true;
378 }
379
380 //---------------------------------------------------------------------------
381 // wxQTMediaBackend::IsQuickTime4Installed
382 //
383 // Determines whether version 4 of QT is installed
384 // (Pretty much for Classic only)
385 //---------------------------------------------------------------------------
386 Boolean wxQTMediaBackend::IsQuickTime4Installed()
387 {
388 OSErr error;
389 long result;
390
391 error = Gestalt(gestaltQuickTime, &result);
392 return (error == noErr) && (((result >> 16) & 0xffff) >= 0x0400);
393 }
394
395 //---------------------------------------------------------------------------
396 // wxQTMediaBackend::Load (file version)
397 //
398 // 1) Get an FSSpec from the Windows path name
399 // 2) Open the movie
400 // 3) Obtain the movie instance from the movie resource
401 // 4) Close the movie resource
402 // 5) Finish loading
403 //---------------------------------------------------------------------------
404 bool wxQTMediaBackend::Load(const wxString& fileName)
405 {
406 if (m_movie)
407 Cleanup();
408
409 ::ClearMoviesStickyError(); // clear previous errors so
410 // GetMoviesStickyError is useful
411
412 OSErr err = noErr;
413 short movieResFile;
414 FSSpec sfFile;
415
416 wxMacFilename2FSSpec( fileName, &sfFile );
417 if (OpenMovieFile( &sfFile, &movieResFile, fsRdPerm ) != noErr)
418 return false;
419
420 short movieResID = 0;
421 Str255 movieName;
422
423 err = NewMovieFromFile(
424 &m_movie,
425 movieResFile,
426 &movieResID,
427 movieName,
428 newMovieActive,
429 NULL); // wasChanged
430
431 //
432 // check GetMoviesStickyError() because it may not find the
433 // proper codec and play black video and other strange effects,
434 // not to mention mess up the dynamic backend loading scheme
435 // of wxMediaCtrl - so it just does what the QuickTime player does
436 //
437 if (err == noErr && ::GetMoviesStickyError() == noErr)
438 {
439 ::CloseMovieFile(movieResFile);
440
441 // Create movie controller/control
442 DoNewMovieController();
443
444 FinishLoad();
445 return true;
446 }
447
448 return false;
449 }
450
451 //---------------------------------------------------------------------------
452 // wxQTMediaBackend::Load (URL Version)
453 //
454 // 1) Build an escaped URI from location
455 // 2) Create a handle to store the URI string
456 // 3) Put the URI string inside the handle
457 // 4) Make a QuickTime URL data ref from the handle with the URI in it
458 // 5) Clean up the URI string handle
459 // 6) Do some prerolling
460 // 7) Finish Loading
461 //---------------------------------------------------------------------------
462 bool wxQTMediaBackend::Load(const wxURI& location)
463 {
464 if (m_movie)
465 Cleanup();
466
467 ::ClearMoviesStickyError(); // clear previous errors so
468 // GetMoviesStickyError is useful
469
470 wxString theURI = location.BuildURI();
471 OSErr err;
472
473 size_t len;
474 const char* theURIString;
475
476 #if wxUSE_UNICODE
477 wxCharBuffer buf = wxConvLocal.cWC2MB(theURI, theURI.length(), &len);
478 theURIString = buf;
479 #else
480 theURIString = theURI;
481 len = theURI.length();
482 #endif
483
484 Handle theHandle = ::NewHandleClear(len + 1);
485 wxASSERT(theHandle);
486
487 ::BlockMoveData(theURIString, *theHandle, len + 1);
488
489 // create the movie from the handle that refers to the URI
490 err = ::NewMovieFromDataRef(
491 &m_movie,
492 newMovieActive | newMovieAsyncOK /* | newMovieIdleImportOK*/,
493 NULL, theHandle,
494 URLDataHandlerSubType);
495
496 ::DisposeHandle(theHandle);
497
498 if (err == noErr && ::GetMoviesStickyError() == noErr)
499 {
500 // Movie controller resets prerolling, so we must create first
501 DoNewMovieController();
502
503 long timeNow;
504 Fixed playRate;
505
506 timeNow = ::GetMovieTime(m_movie, NULL);
507 wxASSERT(::GetMoviesError() == noErr);
508
509 playRate = ::GetMoviePreferredRate(m_movie);
510 wxASSERT(::GetMoviesError() == noErr);
511
512 //
513 // Note that the callback here is optional,
514 // but without it PrePrerollMovie can be buggy
515 // (see Apple ml). Also, some may wonder
516 // why we need this at all - this is because
517 // Apple docs say QuickTime streamed movies
518 // require it if you don't use a Movie Controller,
519 // which we don't by default.
520 //
521 m_preprerollupp =
522 NewMoviePrePrerollCompleteUPP( wxQTMediaBackend::PPRMProc );
523 ::PrePrerollMovie( m_movie, timeNow, playRate,
524 m_preprerollupp, (void*)this);
525
526 return true;
527 }
528
529 return false;
530 }
531
532 //---------------------------------------------------------------------------
533 // wxQTMediaBackend::DoNewMovieController
534 //
535 // Attaches movie to moviecontroller or creates moviecontroller
536 // if not created yet
537 //---------------------------------------------------------------------------
538 void wxQTMediaBackend::DoNewMovieController()
539 {
540 if (!m_mc)
541 {
542 // Get top level window ref for some mac functions
543 WindowRef wrTLW = (WindowRef) m_ctrl->MacGetTopLevelWindowRef();
544
545 // MovieController not set up yet, so we need to create a new one.
546 // You have to pass a valid movie to NewMovieController, evidently
547 ::SetMovieGWorld(m_movie,
548 (CGrafPtr) GetWindowPort(wrTLW),
549 NULL);
550 wxASSERT(::GetMoviesError() == noErr);
551
552 Rect bounds = wxMacGetBoundsForControl(
553 m_ctrl,
554 m_ctrl->GetPosition(),
555 m_ctrl->GetSize());
556
557 m_mc = ::NewMovieController(
558 m_movie, &bounds,
559 mcTopLeftMovie | mcNotVisible /* | mcWithFrame */ );
560 wxASSERT(::GetMoviesError() == noErr);
561
562 ::MCDoAction(m_mc, 32, (void*)true); // mcActionSetKeysEnabled
563 wxASSERT(::GetMoviesError() == noErr);
564
565 // Setup a callback so we can tell when the user presses
566 // play on the player controls
567 m_mcactionupp =
568 NewMCActionFilterWithRefConUPP( wxQTMediaBackend::MCFilterProc );
569 ::MCSetActionFilterWithRefCon( m_mc, m_mcactionupp, (long)this );
570 wxASSERT(::GetMoviesError() == noErr);
571
572 // Part of a suggestion from Greg Hazel to repaint movie when idle
573 m_ctrl->PushEventHandler(new wxQTMediaEvtHandler(this));
574
575 // Create offscreen GWorld for where to "show" when window is hidden
576 Rect worldRect;
577 worldRect.left = worldRect.top = 0;
578 worldRect.right = worldRect.bottom = 1;
579 ::NewGWorld(&m_movieWorld, 0, &worldRect, NULL, NULL, 0);
580
581 // Catch window messages:
582 // if we do not do this and if the user clicks the play
583 // button on the controller, for instance, nothing will happen...
584 EventTypeSpec theWindowEventTypes[] =
585 {
586 { kEventClassMouse, kEventMouseDown },
587 { kEventClassMouse, kEventMouseUp },
588 { kEventClassMouse, kEventMouseDragged },
589 { kEventClassKeyboard, kEventRawKeyDown },
590 { kEventClassKeyboard, kEventRawKeyRepeat },
591 { kEventClassKeyboard, kEventRawKeyUp },
592 { kEventClassWindow, kEventWindowUpdate },
593 { kEventClassWindow, kEventWindowActivated },
594 { kEventClassWindow, kEventWindowDeactivated }
595 };
596 m_windowUPP =
597 NewEventHandlerUPP( wxQTMediaBackend::WindowEventHandler );
598 InstallWindowEventHandler(
599 wrTLW,
600 m_windowUPP,
601 GetEventTypeCount( theWindowEventTypes ), theWindowEventTypes,
602 this,
603 &m_windowEventHandler );
604 }
605 else
606 {
607 // MovieController already created:
608 // Just change the movie in it and we're good to go
609 Point thePoint;
610 thePoint.h = thePoint.v = 0;
611 ::MCSetMovie(m_mc, m_movie,
612 (WindowRef)m_ctrl->MacGetTopLevelWindowRef(),
613 thePoint);
614 wxASSERT(::GetMoviesError() == noErr);
615 }
616 }
617
618 //---------------------------------------------------------------------------
619 // wxQTMediaBackend::FinishLoad
620 //
621 // Performs operations after a movie ready to play/loaded.
622 //---------------------------------------------------------------------------
623 void wxQTMediaBackend::FinishLoad()
624 {
625 // Dispose of the PrePrerollMovieUPP if we used it
626 DisposeMoviePrePrerollCompleteUPP(m_preprerollupp);
627
628 // get the real size of the movie
629 DoLoadBestSize();
630
631 // show the player controls if the user wants to
632 if (m_interfaceflags)
633 DoSetControllerVisible(m_interfaceflags);
634
635 // we want millisecond precision
636 ::SetMovieTimeScale(m_movie, 1000);
637 wxASSERT(::GetMoviesError() == noErr);
638
639 // start movie progress timer
640 m_timer = new wxQTMediaPlayTimer(this);
641 wxASSERT(m_timer);
642 m_timer->Start(MOVIE_DELAY, wxTIMER_CONTINUOUS);
643
644 // send loaded event and refresh size
645 NotifyMovieLoaded();
646 }
647
648 //---------------------------------------------------------------------------
649 // wxQTMediaBackend::DoLoadBestSize
650 //
651 // Sets the best size of the control from the real size of the movie
652 //---------------------------------------------------------------------------
653 void wxQTMediaBackend::DoLoadBestSize()
654 {
655 // get the real size of the movie
656 Rect outRect;
657 ::GetMovieNaturalBoundsRect(m_movie, &outRect);
658 wxASSERT(::GetMoviesError() == noErr);
659
660 // determine best size
661 m_bestSize.x = outRect.right - outRect.left;
662 m_bestSize.y = outRect.bottom - outRect.top;
663 }
664
665 //---------------------------------------------------------------------------
666 // wxQTMediaBackend::Play
667 //
668 // Start the QT movie
669 // (Apple recommends mcActionPrerollAndPlay but that's QT 4.1+)
670 //---------------------------------------------------------------------------
671 bool wxQTMediaBackend::Play()
672 {
673 Fixed fixRate = (Fixed) (wxQTMediaBackend::GetPlaybackRate() * 0x10000);
674 if (!fixRate)
675 fixRate = ::GetMoviePreferredRate(m_movie);
676
677 wxASSERT(fixRate != 0);
678
679 if (!m_bPlaying)
680 ::MCDoAction( m_mc, 8 /* mcActionPlay */, (void*) fixRate);
681
682 bool result = (::GetMoviesError() == noErr);
683 if (result)
684 {
685 m_bPlaying = true;
686 QueuePlayEvent();
687 }
688
689 return result;
690 }
691
692 //---------------------------------------------------------------------------
693 // wxQTMediaBackend::Pause
694 //
695 // Stop the movie
696 //---------------------------------------------------------------------------
697 bool wxQTMediaBackend::DoPause()
698 {
699 // Stop the movie A.K.A. ::StopMovie(m_movie);
700 if (m_bPlaying)
701 {
702 ::MCDoAction( m_mc, 8 /*mcActionPlay*/, (void *) 0);
703 m_bPlaying = false;
704 return ::GetMoviesError() == noErr;
705 }
706
707 // already paused
708 return true;
709 }
710
711 bool wxQTMediaBackend::Pause()
712 {
713 bool bSuccess = DoPause();
714 if (bSuccess)
715 this->QueuePauseEvent();
716
717 return bSuccess;
718 }
719
720 //---------------------------------------------------------------------------
721 // wxQTMediaBackend::Stop
722 //
723 // 1) Stop the movie
724 // 2) Seek to the beginning of the movie
725 //---------------------------------------------------------------------------
726 bool wxQTMediaBackend::DoStop()
727 {
728 if (!wxQTMediaBackend::DoPause())
729 return false;
730
731 ::GoToBeginningOfMovie(m_movie);
732 return ::GetMoviesError() == noErr;
733 }
734
735 bool wxQTMediaBackend::Stop()
736 {
737 bool bSuccess = DoStop();
738 if (bSuccess)
739 QueueStopEvent();
740
741 return bSuccess;
742 }
743
744 //---------------------------------------------------------------------------
745 // wxQTMediaBackend::GetPlaybackRate
746 //
747 // 1) Get the movie playback rate from ::GetMovieRate
748 //---------------------------------------------------------------------------
749 double wxQTMediaBackend::GetPlaybackRate()
750 {
751 return ( ((double)::GetMovieRate(m_movie)) / 0x10000);
752 }
753
754 //---------------------------------------------------------------------------
755 // wxQTMediaBackend::SetPlaybackRate
756 //
757 // 1) Convert dRate to Fixed and Set the movie rate through SetMovieRate
758 //---------------------------------------------------------------------------
759 bool wxQTMediaBackend::SetPlaybackRate(double dRate)
760 {
761 ::SetMovieRate(m_movie, (Fixed) (dRate * 0x10000));
762 return ::GetMoviesError() == noErr;
763 }
764
765 //---------------------------------------------------------------------------
766 // wxQTMediaBackend::SetPosition
767 //
768 // 1) Create a time record struct (TimeRecord) with appropriate values
769 // 2) Pass struct to SetMovieTime
770 //---------------------------------------------------------------------------
771 bool wxQTMediaBackend::SetPosition(wxLongLong where)
772 {
773 TimeRecord theTimeRecord;
774 memset(&theTimeRecord, 0, sizeof(TimeRecord));
775 theTimeRecord.value.lo = where.GetValue();
776 theTimeRecord.scale = ::GetMovieTimeScale(m_movie);
777 theTimeRecord.base = ::GetMovieTimeBase(m_movie);
778 ::SetMovieTime(m_movie, &theTimeRecord);
779
780 if (::GetMoviesError() != noErr)
781 return false;
782
783 return true;
784 }
785
786 //---------------------------------------------------------------------------
787 // wxQTMediaBackend::GetPosition
788 //
789 // Calls GetMovieTime
790 //---------------------------------------------------------------------------
791 wxLongLong wxQTMediaBackend::GetPosition()
792 {
793 return ::GetMovieTime(m_movie, NULL);
794 }
795
796 //---------------------------------------------------------------------------
797 // wxQTMediaBackend::GetVolume
798 //
799 // Gets the volume through GetMovieVolume - which returns a 16 bit short -
800 //
801 // +--------+--------+
802 // + (1) + (2) +
803 // +--------+--------+
804 //
805 // (1) first 8 bits are value before decimal
806 // (2) second 8 bits are value after decimal
807 //
808 // Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to
809 // 1 (full gain and sound)
810 //---------------------------------------------------------------------------
811 double wxQTMediaBackend::GetVolume()
812 {
813 short sVolume = ::GetMovieVolume(m_movie);
814
815 if (sVolume & (128 << 8)) //negative - no sound
816 return 0.0;
817
818 return sVolume / 256.0;
819 }
820
821 //---------------------------------------------------------------------------
822 // wxQTMediaBackend::SetVolume
823 //
824 // Sets the volume through SetMovieVolume - which takes a 16 bit short -
825 //
826 // +--------+--------+
827 // + (1) + (2) +
828 // +--------+--------+
829 //
830 // (1) first 8 bits are value before decimal
831 // (2) second 8 bits are value after decimal
832 //
833 // Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to
834 // 1 (full gain and sound)
835 //---------------------------------------------------------------------------
836 bool wxQTMediaBackend::SetVolume(double dVolume)
837 {
838 ::SetMovieVolume(m_movie, (short) (dVolume * 256));
839 return true;
840 }
841
842 //---------------------------------------------------------------------------
843 // wxQTMediaBackend::GetDuration
844 //
845 // Calls GetMovieDuration
846 //---------------------------------------------------------------------------
847 wxLongLong wxQTMediaBackend::GetDuration()
848 {
849 return ::GetMovieDuration(m_movie);
850 }
851
852 //---------------------------------------------------------------------------
853 // wxQTMediaBackend::GetState
854 //
855 // Determines the current state - the timer keeps track of whether or not
856 // we are paused or stopped (if the timer is running we are playing)
857 //---------------------------------------------------------------------------
858 wxMediaState wxQTMediaBackend::GetState()
859 {
860 // Could use
861 // GetMovieActive/IsMovieDone/SetMovieActive
862 // combo if implemented that way
863 if (m_bPlaying)
864 return wxMEDIASTATE_PLAYING;
865 else if (!m_movie || wxQTMediaBackend::GetPosition() == 0)
866 return wxMEDIASTATE_STOPPED;
867 else
868 return wxMEDIASTATE_PAUSED;
869 }
870
871 //---------------------------------------------------------------------------
872 // wxQTMediaBackend::Cleanup
873 //
874 // Diposes of the movie timer, Control if native, and stops and disposes
875 // of the QT movie
876 //---------------------------------------------------------------------------
877 void wxQTMediaBackend::Cleanup()
878 {
879 m_bPlaying = false;
880 if (m_timer)
881 {
882 delete m_timer;
883 m_timer = NULL;
884 }
885
886 // Stop the movie:
887 // Apple samples with CreateMovieControl typically
888 // install a event handler and do this on the dispose
889 // event, but we do it here for simplicity
890 // (It might keep playing for several seconds after
891 // control destruction if not)
892 wxQTMediaBackend::Pause();
893
894 // Dispose of control or remove movie from MovieController
895 Point thePoint;
896 thePoint.h = thePoint.v = 0;
897 ::MCSetVisible(m_mc, false);
898 ::MCSetMovie(m_mc, NULL, NULL, thePoint);
899
900 ::DisposeMovie(m_movie);
901 m_movie = NULL;
902 }
903
904 //---------------------------------------------------------------------------
905 // wxQTMediaBackend::GetVideoSize
906 //
907 // Returns the actual size of the QT movie
908 //---------------------------------------------------------------------------
909 wxSize wxQTMediaBackend::GetVideoSize() const
910 {
911 return m_bestSize;
912 }
913
914 //---------------------------------------------------------------------------
915 // wxQTMediaBackend::Move
916 //
917 // Move the movie controller or movie control
918 // (we need to actually move the movie control manually...)
919 // Top 10 things to do with quicktime in March 93's issue
920 // of DEVELOP - very useful
921 // http:// www.mactech.com/articles/develop/issue_13/031-033_QuickTime_column.html
922 // OLD NOTE: Calling MCSetControllerBoundsRect without detaching
923 // supposively resulted in a crash back then. Current code even
924 // with CFM classic runs fine. If there is ever a problem,
925 // take out the if 0 lines below
926 //---------------------------------------------------------------------------
927 void wxQTMediaBackend::Move(int x, int y, int w, int h)
928 {
929 if (m_timer)
930 {
931 m_ctrl->GetParent()->MacWindowToRootWindow(&x, &y);
932 Rect theRect = {y, x, y + h, x + w};
933
934 #if 0 // see note above
935 ::MCSetControllerAttached(m_mc, false);
936 wxASSERT(::GetMoviesError() == noErr);
937 #endif
938
939 ::MCSetControllerBoundsRect(m_mc, &theRect);
940 wxASSERT(::GetMoviesError() == noErr);
941
942 #if 0 // see note above
943 if (m_interfaceflags)
944 {
945 ::MCSetVisible(m_mc, true);
946 wxASSERT(::GetMoviesError() == noErr);
947 }
948 #endif
949 }
950 }
951
952 //---------------------------------------------------------------------------
953 // wxQTMediaBackend::DoSetControllerVisible
954 //
955 // Utility function that takes care of showing the moviecontroller
956 // and showing/hiding the particular controls on it
957 //---------------------------------------------------------------------------
958 void wxQTMediaBackend::DoSetControllerVisible(
959 wxMediaCtrlPlayerControls flags)
960 {
961 ::MCSetVisible(m_mc, true);
962
963 // Take care of subcontrols
964 if (::GetMoviesError() == noErr)
965 {
966 long mcFlags = 0;
967 ::MCDoAction(m_mc, 39/*mcActionGetFlags*/, (void*)&mcFlags);
968
969 if (::GetMoviesError() == noErr)
970 {
971 mcFlags |= ( //(1<<0)/*mcFlagSuppressMovieFrame*/ |
972 (1 << 3)/*mcFlagsUseWindowPalette*/
973 | ((flags & wxMEDIACTRLPLAYERCONTROLS_STEP)
974 ? 0 : (1 << 1)/*mcFlagSuppressStepButtons*/)
975 | ((flags & wxMEDIACTRLPLAYERCONTROLS_VOLUME)
976 ? 0 : (1 << 2)/*mcFlagSuppressSpeakerButton*/)
977 //if we take care of repainting ourselves
978 // | (1 << 4) /*mcFlagDontInvalidate*/
979 );
980
981 ::MCDoAction(m_mc, 38/*mcActionSetFlags*/, (void*)mcFlags);
982 }
983 }
984
985 // Adjust height and width of best size for movie controller
986 // if the user wants it shown
987 m_bestSize.x = m_bestSize.x > wxMCWIDTH ? m_bestSize.x : wxMCWIDTH;
988 m_bestSize.y += wxMCHEIGHT;
989 }
990
991 //---------------------------------------------------------------------------
992 // wxQTMediaBackend::ShowPlayerControls
993 //
994 // Shows/Hides subcontrols on the media control
995 //---------------------------------------------------------------------------
996 bool wxQTMediaBackend::ShowPlayerControls(wxMediaCtrlPlayerControls flags)
997 {
998 if (!m_mc)
999 return false; // no movie controller...
1000
1001 bool bSizeChanged = false;
1002
1003 // if the controller is visible and we want to hide it do so
1004 if (m_interfaceflags && !flags)
1005 {
1006 bSizeChanged = true;
1007 DoLoadBestSize();
1008 ::MCSetVisible(m_mc, false);
1009 }
1010 else if (!m_interfaceflags && flags) // show controller if hidden
1011 {
1012 bSizeChanged = true;
1013 DoSetControllerVisible(flags);
1014 }
1015
1016 // readjust parent sizers
1017 if (bSizeChanged)
1018 {
1019 NotifyMovieSizeChanged();
1020
1021 // remember state in case of loading new media
1022 m_interfaceflags = flags;
1023 }
1024
1025 return ::GetMoviesError() == noErr;
1026 }
1027
1028 //---------------------------------------------------------------------------
1029 // wxQTMediaBackend::GetDataSizeFromStart
1030 //
1031 // Calls either GetMovieDataSize or GetMovieDataSize64 with a value
1032 // of 0 for the starting value
1033 //---------------------------------------------------------------------------
1034 wxLongLong wxQTMediaBackend::GetDataSizeFromStart(TimeValue end)
1035 {
1036 #if 0 // old pre-qt4 way
1037 return ::GetMovieDataSize(m_movie, 0, end)
1038 #else // qt4 way
1039 wide llDataSize;
1040 ::GetMovieDataSize64(m_movie, 0, end, &llDataSize);
1041 return wxLongLong(llDataSize.hi, llDataSize.lo);
1042 #endif
1043 }
1044
1045 //---------------------------------------------------------------------------
1046 // wxQTMediaBackend::GetDownloadProgress
1047 //---------------------------------------------------------------------------
1048 wxLongLong wxQTMediaBackend::GetDownloadProgress()
1049 {
1050 #if 0 // hackish and slow
1051 Handle hMovie = NewHandle(0);
1052 PutMovieIntoHandle(m_movie, hMovie);
1053 long lSize = GetHandleSize(hMovie);
1054 DisposeHandle(hMovie);
1055
1056 return lSize;
1057 #else
1058 TimeValue tv;
1059 if (::GetMaxLoadedTimeInMovie(m_movie, &tv) != noErr)
1060 {
1061 wxLogDebug(wxT("GetMaxLoadedTimeInMovie failed"));
1062 return 0;
1063 }
1064
1065 return wxQTMediaBackend::GetDataSizeFromStart(tv);
1066 #endif
1067 }
1068
1069 //---------------------------------------------------------------------------
1070 // wxQTMediaBackend::GetDownloadTotal
1071 //---------------------------------------------------------------------------
1072 wxLongLong wxQTMediaBackend::GetDownloadTotal()
1073 {
1074 return wxQTMediaBackend::GetDataSizeFromStart(
1075 ::GetMovieDuration(m_movie)
1076 );
1077 }
1078
1079 //---------------------------------------------------------------------------
1080 // wxQTMediaBackend::MacVisibilityChanged
1081 //
1082 // The main problem here is that Windows quicktime, for example,
1083 // renders more directly to a HWND. Mac quicktime does not do this
1084 // and instead renders to the port of the WindowRef/WindowPtr on top
1085 // of everything else/all other windows.
1086 //
1087 // So, for example, if you were to have a CreateTabsControl/wxNotebook
1088 // and change pages, even if you called HIViewSetVisible/SetControlVisibility
1089 // directly the movie will still continue playing on top of everything else
1090 // if you went to a different tab.
1091 //
1092 // Note that another issue, and why we call MCSetControllerPort instead
1093 // of SetMovieGWorld directly, is that in addition to rendering on
1094 // top of everything else the last created controller steals mouse and
1095 // other input from everything else in the window, including other
1096 // controllers. Setting the port of it releases this behaviour.
1097 //---------------------------------------------------------------------------
1098 void wxQTMediaBackend::MacVisibilityChanged()
1099 {
1100 if(!m_mc || !m_ctrl->m_bLoaded)
1101 return; //not initialized yet
1102
1103 if(m_ctrl->MacIsReallyShown())
1104 {
1105 //The window is being shown again, so set the GWorld of the
1106 //controller back to the port of the parent WindowRef
1107 WindowRef wrTLW =
1108 (WindowRef) m_ctrl->MacGetTopLevelWindowRef();
1109
1110 ::MCSetControllerPort(m_mc, (CGrafPtr) GetWindowPort(wrTLW));
1111 wxASSERT(::GetMoviesError() == noErr);
1112 }
1113 else
1114 {
1115 //We are being hidden - set the GWorld of the controller
1116 //to the offscreen GWorld
1117 ::MCSetControllerPort(m_mc, m_movieWorld);
1118 wxASSERT(::GetMoviesError() == noErr);
1119 }
1120 }
1121
1122 //---------------------------------------------------------------------------
1123 // wxQTMediaBackend::OnEraseBackground
1124 //
1125 // Suggestion from Greg Hazel to repaint the movie when idle
1126 // (on pause also)
1127 //---------------------------------------------------------------------------
1128 void wxQTMediaEvtHandler::OnEraseBackground(wxEraseEvent& evt)
1129 {
1130 // Work around Nasty OSX drawing bug:
1131 // http://lists.apple.com/archives/QuickTime-API/2002/Feb/msg00311.html
1132 WindowRef wrTLW = (WindowRef) m_qtb->m_ctrl->MacGetTopLevelWindowRef();
1133
1134 RgnHandle region = ::MCGetControllerBoundsRgn(m_qtb->m_mc);
1135 ::MCInvalidate(m_qtb->m_mc, wrTLW, region);
1136 ::MCIdle(m_qtb->m_mc);
1137 }
1138
1139 //---------------------------------------------------------------------------
1140 // wxQTMediaBackend::PPRMProc (static)
1141 //
1142 // Called when done PrePrerolling the movie.
1143 // Note that in 99% of the cases this does nothing...
1144 // Anyway we set up the loading timer here to tell us when the movie is done
1145 //---------------------------------------------------------------------------
1146 pascal void wxQTMediaBackend::PPRMProc(
1147 Movie theMovie,
1148 OSErr WXUNUSED_UNLESS_DEBUG(theErr),
1149 void* theRefCon)
1150 {
1151 wxASSERT( theMovie );
1152 wxASSERT( theRefCon );
1153 wxASSERT( theErr == noErr );
1154
1155 wxQTMediaBackend* pBE = (wxQTMediaBackend*) theRefCon;
1156
1157 long lTime = ::GetMovieTime(theMovie,NULL);
1158 Fixed rate = ::GetMoviePreferredRate(theMovie);
1159 ::PrerollMovie(theMovie,lTime,rate);
1160 pBE->m_timer = new wxQTMediaLoadTimer(pBE);
1161 pBE->m_timer->Start(MOVIE_DELAY);
1162 }
1163
1164 //---------------------------------------------------------------------------
1165 // wxQTMediaBackend::MCFilterProc (static)
1166 //
1167 // Callback for when the movie controller recieves a message
1168 //---------------------------------------------------------------------------
1169 pascal Boolean wxQTMediaBackend::MCFilterProc(
1170 MovieController WXUNUSED(theController),
1171 short action,
1172 void * WXUNUSED(params),
1173 long refCon)
1174 {
1175 wxQTMediaBackend* pThis = (wxQTMediaBackend*)refCon;
1176
1177 switch (action)
1178 {
1179 case 1:
1180 // don't process idle events
1181 break;
1182
1183 case 8:
1184 // play button triggered - MC will set movie to opposite state
1185 // of current - playing ? paused : playing
1186 pThis->m_bPlaying = !(pThis->m_bPlaying);
1187 break;
1188
1189 default:
1190 break;
1191 }
1192
1193 return 0;
1194 }
1195
1196 //---------------------------------------------------------------------------
1197 // wxQTMediaBackend::WindowEventHandler [static]
1198 //
1199 // Event callback for the top level window of our control that passes
1200 // messages to our moviecontroller so it can receive mouse clicks etc.
1201 //---------------------------------------------------------------------------
1202 pascal OSStatus wxQTMediaBackend::WindowEventHandler(
1203 EventHandlerCallRef inHandlerCallRef,
1204 EventRef inEvent,
1205 void *inUserData)
1206 {
1207 wxQTMediaBackend* be = (wxQTMediaBackend*) inUserData;
1208
1209 // Only process keyboard messages on this window if it actually
1210 // has focus, otherwise it will steal keystrokes from other windows!
1211 // As well as when it is not loaded properly as it
1212 // will crash in MCIsPlayerEvent
1213 if((GetEventClass(inEvent) == kEventClassKeyboard &&
1214 wxWindow::FindFocus() != be->m_ctrl)
1215 || !be->m_ctrl->m_bLoaded)
1216 return eventNotHandledErr;
1217
1218 // Pass the event onto the movie controller
1219 EventRecord theEvent;
1220 ConvertEventRefToEventRecord( inEvent, &theEvent );
1221 OSStatus err;
1222
1223 // TODO: Apple says MCIsPlayerEvent is depreciated and
1224 // MCClick, MCKey, MCIdle etc. should be used
1225 // (RN: Of course that's what they say about
1226 // CreateMovieControl and HIMovieView as well, LOL!)
1227 err = ::MCIsPlayerEvent( be->m_mc, &theEvent );
1228
1229 // Pass on to other event handlers if not handled- i.e. wx
1230 if (err != noErr)
1231 return noErr;
1232 else
1233 return eventNotHandledErr;
1234 }
1235
1236 // in source file that contains stuff you don't directly use
1237 #include "wx/html/forcelnk.h"
1238 FORCE_LINK_ME(basewxmediabackends)
1239
1240 #endif // wxUSE_MEDIACTRL