]> git.sesse.net Git - vlc/blob - projects/macosx/framework/Sources/VLCMediaPlayer.m
osx/framework: added a bit more exception handling
[vlc] / projects / macosx / framework / Sources / VLCMediaPlayer.m
1 /*****************************************************************************
2  * VLCMediaPlayer.m: VLCKit.framework VLCMediaPlayer implementation
3  *****************************************************************************
4  * Copyright (C) 2007-2009 Pierre d'Herbemont
5  * Copyright (C) 2007-2009 the VideoLAN team
6  * Partial Copyright (C) 2009 Felix Paul Kühne
7  * $Id$
8  *
9  * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
10  *          Faustion Osuna <enrique.osuna # gmail.com>
11  *          Felix Paul Kühne <fkuehne # videolan.org>
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #import "VLCLibrary.h"
29 #import "VLCMediaPlayer.h"
30 #import "VLCEventManager.h"
31 #import "VLCLibVLCBridging.h"
32 #import "VLCVideoView.h"
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36
37 /* prevent system sleep */
38 #import <CoreServices/CoreServices.h>
39 /* FIXME: Ugly hack! */
40 #ifdef __x86_64__
41 #import <CoreServices/../Frameworks/OSServices.framework/Headers/Power.h>
42 #endif
43
44 #include <vlc/vlc.h>
45
46 /* Notification Messages */
47 NSString * VLCMediaPlayerTimeChanged    = @"VLCMediaPlayerTimeChanged";
48 NSString * VLCMediaPlayerStateChanged   = @"VLCMediaPlayerStateChanged";
49
50 NSString * VLCMediaPlayerStateToString(VLCMediaPlayerState state)
51 {
52     static NSString * stateToStrings[] = {
53         [VLCMediaPlayerStateStopped]      = @"VLCMediaPlayerStateStopped",
54         [VLCMediaPlayerStateOpening]      = @"VLCMediaPlayerStateOpening",
55         [VLCMediaPlayerStateBuffering]    = @"VLCMediaPlayerStateBuffering",
56         [VLCMediaPlayerStateEnded]        = @"VLCMediaPlayerStateEnded",
57         [VLCMediaPlayerStateError]        = @"VLCMediaPlayerStateError",
58         [VLCMediaPlayerStatePlaying]      = @"VLCMediaPlayerStatePlaying",
59         [VLCMediaPlayerStatePaused]       = @"VLCMediaPlayerStatePaused"
60     };
61     return stateToStrings[state];
62 }
63
64 /* libvlc event callback */
65 static void HandleMediaInstanceVolumeChanged(const libvlc_event_t * event, void * self)
66 {
67     [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
68                                                    withDelegateMethod:@selector(mediaPlayerVolumeChanged:)
69                                                  withNotificationName:VLCMediaPlayerVolumeChanged];
70 }
71
72 static void HandleMediaTimeChanged(const libvlc_event_t * event, void * self)
73 {
74     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
75     [[VLCEventManager sharedManager] callOnMainThreadObject:self 
76                                                  withMethod:@selector(mediaPlayerTimeChanged:) 
77                                        withArgumentAsObject:[NSNumber numberWithLongLong:event->u.media_player_time_changed.new_time]];
78
79     [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
80                                                    withDelegateMethod:@selector(mediaPlayerTimeChanged:)
81                                                  withNotificationName:VLCMediaPlayerTimeChanged];
82     [pool release];
83 }
84
85 static void HandleMediaPositionChanged(const libvlc_event_t * event, void * self)
86 {
87     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
88
89     [[VLCEventManager sharedManager] callOnMainThreadObject:self 
90                                                  withMethod:@selector(mediaPlayerPositionChanged:) 
91                                        withArgumentAsObject:[NSNumber numberWithFloat:event->u.media_player_position_changed.new_position]];
92     [pool release];
93 }
94
95 static void HandleMediaInstanceStateChanged(const libvlc_event_t * event, void * self)
96 {
97     VLCMediaPlayerState newState;
98
99     if( event->type == libvlc_MediaPlayerPlaying )
100         newState = VLCMediaPlayerStatePlaying;
101     else if( event->type == libvlc_MediaPlayerPaused )
102         newState = VLCMediaPlayerStatePaused;
103     else if( event->type == libvlc_MediaPlayerEndReached )
104         newState = VLCMediaPlayerStateStopped;
105     else if( event->type == libvlc_MediaPlayerEncounteredError )
106         newState = VLCMediaPlayerStateError;
107     else
108     {
109         NSLog(@"%s: Unknown event", __FUNCTION__);
110         return;
111     }
112
113     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
114
115     [[VLCEventManager sharedManager] callOnMainThreadObject:self 
116                                                  withMethod:@selector(mediaPlayerStateChanged:) 
117                                        withArgumentAsObject:[NSNumber numberWithInt:newState]];
118
119     [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
120                                                    withDelegateMethod:@selector(mediaPlayerStateChanged:)
121                                                  withNotificationName:VLCMediaPlayerStateChanged];
122
123     [pool release];
124
125 }
126
127
128 // TODO: Documentation
129 @interface VLCMediaPlayer (Private)
130 - (id)initWithDrawable:(id)aDrawable;
131
132 - (void)registerObservers;
133 - (void)unregisterObservers;
134 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime;
135 - (void)mediaPlayerPositionChanged:(NSNumber *)newTime;
136 - (void)mediaPlayerStateChanged:(NSNumber *)newState;
137 @end
138
139 @implementation VLCMediaPlayer
140
141 /* Bindings */
142 + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
143 {
144     static NSDictionary * dict = nil;
145     NSSet * superKeyPaths;
146     if( !dict )
147     {
148         dict = [[NSDictionary dictionaryWithObjectsAndKeys:
149             [NSSet setWithObject:@"state"], @"playing",
150             [NSSet setWithObjects:@"state", @"media", nil], @"seekable",
151             [NSSet setWithObjects:@"state", @"media", nil], @"canPause",
152             [NSSet setWithObjects:@"state", @"media", nil], @"description",
153             nil] retain];
154     }
155     if( (superKeyPaths = [super keyPathsForValuesAffectingValueForKey: key]) )
156     {
157         NSMutableSet * ret = [NSMutableSet setWithSet:[dict objectForKey: key]];
158         [ret unionSet:superKeyPaths];
159         return ret;
160     }
161     return [dict objectForKey: key];
162 }
163
164 /* Contructor */
165 - (id)init
166 {
167     return [self initWithDrawable:nil];
168 }
169
170 - (id)initWithVideoView:(VLCVideoView *)aVideoView
171 {
172     return [self initWithDrawable: aVideoView];
173 }
174
175 - (id)initWithVideoLayer:(VLCVideoLayer *)aVideoLayer
176 {
177     return [self initWithDrawable: aVideoLayer];
178 }
179
180 - (void)release
181 {
182     @synchronized(self)
183     {
184         if([self retainCount] <= 1)
185         {
186             /* We must make sure we won't receive new event after an upcoming dealloc
187              * We also may receive a -retain in some event callback that may occcur
188              * Before libvlc_event_detach. So this can't happen in dealloc */
189             [self unregisterObservers];
190         }
191         [super release];
192     }
193 }
194
195 - (void)dealloc
196 {
197     NSAssert(libvlc_media_player_get_state(instance, NULL) == libvlc_Stopped, @"You released the media player before ensuring that it is stopped");
198
199     // Always get rid of the delegate first so we can stop sending messages to it
200     // TODO: Should we tell the delegate that we're shutting down?
201     delegate = nil;
202
203     // Clear our drawable as we are going to release it, we don't
204     // want the core to use it from this point. This won't happen as
205     // the media player must be stopped.
206     libvlc_media_player_set_nsobject(instance, nil, NULL);
207
208     libvlc_media_player_release(instance);
209     
210     // Get rid of everything else
211     [media release];
212     [cachedTime release];
213     [drawable release];
214
215     [super dealloc];
216 }
217
218 - (void)setDelegate:(id)value
219 {
220     delegate = value;
221 }
222
223 - (id)delegate
224 {
225     return delegate;
226 }
227
228 - (void)setVideoView:(VLCVideoView *)aVideoView
229 {    
230     [self setDrawable: aVideoView];
231 }
232
233 - (void)setVideoLayer:(VLCVideoLayer *)aVideoLayer
234 {
235     [self setDrawable: aVideoLayer];
236 }
237
238 - (void)setDrawable:(id)aDrawable
239 {
240     // Make sure that this instance has been associated with the drawing canvas.
241     libvlc_exception_t ex;
242     libvlc_exception_init( &ex );
243     libvlc_media_player_set_nsobject(instance, aDrawable, &ex);
244     catch_exception( &ex );
245 }
246
247 - (id)drawable
248 {
249     libvlc_exception_t ex;
250     libvlc_exception_init( &ex );
251     id ret = libvlc_media_player_get_nsobject(instance);
252     catch_exception( &ex );
253     return ret;
254 }
255
256 - (VLCAudio *)audio
257 {
258     return [[VLCLibrary sharedLibrary] audio];
259 }
260
261 - (void)setVideoAspectRatio:(char *)value
262 {
263     libvlc_exception_t ex;
264     libvlc_exception_init( &ex );
265     libvlc_video_set_aspect_ratio( instance, value, &ex );
266     catch_exception( &ex );
267 }
268
269 - (char *)videoAspectRatio
270 {
271     libvlc_exception_t ex;
272     libvlc_exception_init( &ex );
273     char * result = libvlc_video_get_aspect_ratio( instance, &ex );
274     catch_exception( &ex );
275     return result;
276 }
277
278 - (void)setVideoSubTitles:(int)value
279 {
280     libvlc_exception_t ex;
281     libvlc_exception_init( &ex );
282     libvlc_video_set_spu( instance, value, &ex );
283     catch_exception( &ex );
284 }
285
286 - (int)videoSubTitles
287 {
288     libvlc_exception_t ex;
289     libvlc_exception_init( &ex );
290     int result = libvlc_video_get_spu( instance, &ex );
291     catch_exception( &ex );
292     return result;
293 }
294
295 - (void)setVideoCropGeometry:(char *)value
296 {
297     libvlc_exception_t ex;
298     libvlc_exception_init( &ex );
299     libvlc_video_set_crop_geometry( instance, value, &ex );
300     catch_exception( &ex );
301 }
302
303 - (char *)videoCropGeometry
304 {
305     libvlc_exception_t ex;
306     libvlc_exception_init( &ex );
307     char * result = libvlc_video_get_crop_geometry( instance, &ex );
308     catch_exception( &ex );
309     return result;
310 }
311
312 - (void)setVideoTeleText:(int)value
313 {
314     libvlc_exception_t ex;
315     libvlc_exception_init( &ex );
316     libvlc_video_set_teletext( instance, value, &ex );
317     catch_exception( &ex );
318 }
319
320 - (int)videoTeleText
321 {
322     libvlc_exception_t ex;
323     libvlc_exception_init( &ex );
324     int result = libvlc_video_get_teletext( instance, &ex );
325     catch_exception( &ex );
326     return result;
327 }
328
329 - (void)saveVideoSnapshotAt: (NSString *)path withWidth:(NSUInteger)width andHeight:(NSUInteger)height
330 {
331     libvlc_exception_t ex;
332     libvlc_exception_init( &ex );
333     libvlc_video_take_snapshot( instance, [path UTF8String], width, height, &ex );
334     catch_exception( &ex );
335 }
336
337 - (void)setDeinterlaceFilter: (NSString *)name enabled: (BOOL)enabled
338 {
339     libvlc_exception_t ex;
340     libvlc_exception_init( &ex );
341     libvlc_video_set_deinterlace( instance, (int)enabled , [name UTF8String], &ex );
342     catch_exception( &ex );
343 }
344
345 - (void)setRate:(float)value
346 {
347     libvlc_exception_t ex;
348     libvlc_exception_init( &ex );
349     libvlc_media_player_set_rate( instance, value, &ex );
350     catch_exception( &ex );
351 }
352
353 - (float)rate
354 {
355     libvlc_exception_t ex;
356     libvlc_exception_init( &ex );
357     float result = libvlc_media_player_get_rate( instance, &ex );
358     catch_exception( &ex );
359     return result;
360 }
361
362 - (NSSize)videoSize
363 {
364     libvlc_exception_t ex;
365     libvlc_exception_init( &ex );
366     NSSize result = NSMakeSize(libvlc_video_get_height((libvlc_media_player_t *)instance, &ex),
367                                libvlc_video_get_width((libvlc_media_player_t *)instance, &ex));
368     catch_exception( &ex );
369     return result;
370 }
371
372 - (BOOL)hasVideoOut
373 {
374     libvlc_exception_t ex;
375     libvlc_exception_init( &ex );
376     BOOL result = libvlc_media_player_has_vout((libvlc_media_player_t *)instance, &ex);
377     if (libvlc_exception_raised( &ex ))
378     {
379         libvlc_exception_clear( &ex );
380         return NO;
381     }
382     else
383         return result;
384 }
385
386 - (float)framesPerSecond
387 {
388     libvlc_exception_t ex;
389     libvlc_exception_init( &ex );
390     float result = libvlc_media_player_get_fps( (libvlc_media_player_t *)instance, &ex );
391     catch_exception( &ex );
392     return result;
393 }
394
395 - (void)setTime:(VLCTime *)value
396 {
397     libvlc_exception_t ex;
398     libvlc_exception_init( &ex );
399     // Time is managed in seconds, while duration is managed in microseconds
400     // TODO: Redo VLCTime to provide value numberAsMilliseconds, numberAsMicroseconds, numberAsSeconds, numberAsMinutes, numberAsHours
401     libvlc_media_player_set_time( (libvlc_media_player_t *)instance, 
402                                     (value ? [[value numberValue] longLongValue] / 1000 : 0),
403                                     &ex );
404     catch_exception( &ex );
405 }
406
407 - (VLCTime *)time
408 {
409     return cachedTime;
410 }
411
412 - (VLCTime *)remainingTime
413 {
414     double currentTime = [[cachedTime numberValue] doubleValue];
415     double remaining = currentTime / position * (1 - position);
416     return [VLCTime timeWithNumber:[NSNumber numberWithDouble:-remaining]];
417 }
418
419 - (int)fps
420 {
421     libvlc_exception_t ex;
422     libvlc_exception_init( &ex );
423     int result = libvlc_media_player_get_fps( instance, &ex );
424     catch_exception( &ex );
425     return result;
426 }
427
428 - (void)setChapter:(int)value;
429 {
430     libvlc_exception_t ex;
431     libvlc_exception_init( &ex );
432     libvlc_media_player_set_chapter( instance, value, &ex );
433     catch_exception( &ex );
434 }
435
436 - (int)chapter
437 {
438     libvlc_exception_t ex;
439     libvlc_exception_init( &ex );
440     int result = libvlc_media_player_get_chapter( instance, &ex );
441     catch_exception( &ex );
442     return result;
443 }
444
445 - (int)countOfChapters
446 {
447     libvlc_exception_t ex;
448     libvlc_exception_init( &ex );
449     int result = libvlc_media_player_get_chapter_count( instance, &ex );
450     catch_exception( &ex );
451     return result;
452 }
453
454 - (void)nextChapter
455 {
456     libvlc_exception_t ex;
457     libvlc_exception_init( &ex );
458     libvlc_media_player_next_chapter( instance, &ex );
459     catch_exception( &ex );
460 }
461
462 - (void)previousChapter
463 {
464     libvlc_exception_t ex;
465     libvlc_exception_init( &ex );
466     libvlc_media_player_previous_chapter( instance, &ex );
467     catch_exception( &ex );
468 }
469
470 - (void)setTitle:(int)value
471 {
472     libvlc_exception_t ex;
473     libvlc_exception_init( &ex );
474     libvlc_media_player_set_title( instance, value, &ex );
475     catch_exception( &ex );
476 }
477
478 - (int)title
479 {
480     libvlc_exception_t ex;
481     libvlc_exception_init( &ex );
482     int result = libvlc_media_player_get_title( instance, &ex );
483     catch_exception( &ex );
484     return result;
485 }
486
487 - (int)countOfTitles
488 {
489     libvlc_exception_t ex;
490     libvlc_exception_init( &ex );
491     int result = libvlc_media_player_get_title_count( instance, &ex );
492     catch_exception( &ex );
493     return result;
494 }
495
496 - (void)setAudioTrack:(int)value
497 {
498     libvlc_exception_t ex;
499     libvlc_exception_init( &ex );
500     libvlc_audio_set_track( instance, value, &ex );
501     catch_exception( &ex );
502 }
503
504 - (int)audioTrack
505 {
506     libvlc_exception_t ex;
507     libvlc_exception_init( &ex );
508     int result = libvlc_audio_get_track( instance, &ex );
509     catch_exception( &ex );
510     return result;
511 }
512
513 - (int)countOfAudioTracks
514 {
515     libvlc_exception_t ex;
516     libvlc_exception_init( &ex );
517     int result = libvlc_audio_get_track_count( instance, &ex );
518     catch_exception( &ex );
519     return result;
520 }
521
522 - (void)setAudioChannel:(int)value
523 {
524     libvlc_exception_t ex;
525     libvlc_exception_init( &ex );
526     libvlc_audio_set_channel( instance, value, &ex );
527     catch_exception( &ex );
528 }
529
530 - (int)audioChannel
531 {
532     libvlc_exception_t ex;
533     libvlc_exception_init( &ex );
534     int result = libvlc_audio_get_channel( instance, &ex );
535     catch_exception( &ex );
536     return result;
537 }
538
539 - (void)setMedia:(VLCMedia *)value
540 {
541     if (media != value)
542     {
543         if (media && [media compare:value] == NSOrderedSame)
544             return;
545         
546         [media release];
547         media = [value retain];
548
549         libvlc_exception_t ex;
550         libvlc_exception_init( &ex );
551         libvlc_media_player_set_media( instance, [media libVLCMediaDescriptor], &ex );
552         catch_exception( &ex );
553     }
554 }
555
556 - (VLCMedia *)media
557 {
558     return media;
559 }
560
561 - (BOOL)play
562 {    
563     libvlc_exception_t ex;
564     libvlc_exception_init( &ex );
565     libvlc_media_player_play( (libvlc_media_player_t *)instance, &ex );
566     catch_exception( &ex );
567     return YES;
568 }
569
570 - (void)pause
571 {
572     if( [NSThread isMainThread] )
573     {
574         /* Hack because we create a dead lock here, when the vout is stopped
575          * and tries to recontact us on the main thread */
576         /* FIXME: to do this properly we need to do some locking. We may want 
577          * to move that to libvlc */
578         [self performSelectorInBackground:@selector(pause) withObject:nil];
579         return;
580     }
581
582     // Pause the stream
583     libvlc_exception_t ex;
584     libvlc_exception_init( &ex );
585     libvlc_media_player_pause( (libvlc_media_player_t *)instance, &ex );
586     catch_exception( &ex );
587 }
588
589 - (void)stop
590 {
591     libvlc_exception_t ex;
592     libvlc_exception_init( &ex );
593     libvlc_media_player_stop((libvlc_media_player_t *)instance, &ex);
594     catch_exception( &ex );
595 }
596
597 - (void)fastForward
598 {
599     [self fastForwardAtRate: 2.0];
600 }
601
602 - (void)fastForwardAtRate:(float)rate
603 {
604     [self setRate:rate];
605 }
606
607 - (void)rewind
608 {
609     [self rewindAtRate: 2.0];
610 }
611
612 - (void)rewindAtRate:(float)rate
613 {
614     [self setRate: -rate];
615 }
616
617 - (void)jumpBackward:(NSInteger)interval
618 {
619     if( [self isSeekable] )
620     {
621         interval = interval * 1000000;
622         [self setTime: [VLCTime timeWithInt: ([[self time] intValue] - interval)]];
623     }
624 }
625
626 - (void)jumpForward:(NSInteger)interval
627 {
628     if( [self isSeekable] )
629     {
630         interval = interval * 1000000;
631         [self setTime: [VLCTime timeWithInt: ([[self time] intValue] + interval)]];
632     }
633 }
634
635 - (void)extraShortJumpBackward
636 {
637     [self jumpBackward:3];
638 }
639
640 - (void)extraShortJumpForward
641 {
642     [self jumpForward:3];
643 }
644
645 - (void)shortJumpBackward
646 {
647     [self jumpBackward:10];
648 }
649
650 - (void)shortJumpForward
651 {
652     [self jumpForward:10];
653 }
654
655 - (void)mediumJumpBackward
656 {
657     [self jumpBackward:60];
658 }
659
660 - (void)mediumJumpForward
661 {
662     [self jumpForward:60];
663 }
664
665 - (void)longJumpBackward
666 {
667     [self jumpBackward:300];
668 }
669
670 - (void)longJumpForward
671 {
672     [self jumpForward:300];
673 }
674
675 + (NSSet *)keyPathsForValuesAffectingIsPlaying
676 {
677     return [NSSet setWithObjects:@"state", nil];
678 }
679
680 - (BOOL)isPlaying
681 {
682     VLCMediaPlayerState state = [self state];
683     return ((state == VLCMediaPlayerStateOpening) || (state == VLCMediaPlayerStateBuffering) ||
684             (state == VLCMediaPlayerStatePlaying));
685 }
686
687 - (BOOL)willPlay
688 {
689     libvlc_exception_t ex;
690     libvlc_exception_init( &ex );
691     BOOL ret = libvlc_media_player_will_play( (libvlc_media_player_t *)instance, &ex );
692     if (libvlc_exception_raised(&ex))
693     {
694         libvlc_exception_clear(&ex);
695         return NO;
696     }
697     else
698         return ret;
699 }
700
701 static const VLCMediaPlayerState libvlc_to_local_state[] =
702 {
703     [libvlc_Stopped]    = VLCMediaPlayerStateStopped,
704     [libvlc_Opening]    = VLCMediaPlayerStateOpening,
705     [libvlc_Buffering]  = VLCMediaPlayerStateBuffering,
706     [libvlc_Playing]    = VLCMediaPlayerStatePlaying,
707     [libvlc_Paused]     = VLCMediaPlayerStatePaused,
708     [libvlc_Ended]      = VLCMediaPlayerStateEnded,
709     [libvlc_Error]      = VLCMediaPlayerStateError
710 };
711
712 - (VLCMediaPlayerState)state
713 {
714     return cachedState;
715 }
716
717 - (float)position
718 {
719     return position;
720 }
721
722 - (void)setPosition:(float)newPosition
723 {
724     libvlc_exception_t ex;
725     libvlc_exception_init( &ex );
726     libvlc_media_player_set_position( instance, newPosition, &ex );
727     catch_exception( &ex );
728 }
729
730 - (BOOL)isSeekable
731 {
732     libvlc_exception_t ex;
733     libvlc_exception_init( &ex );
734     BOOL ret = libvlc_media_player_is_seekable( instance, &ex );
735     catch_exception( &ex );
736     return ret;
737 }
738
739 - (BOOL)canPause
740 {
741     libvlc_exception_t ex;
742     libvlc_exception_init( &ex );
743     BOOL ret = libvlc_media_player_can_pause( instance, &ex );
744     catch_exception( &ex );
745     return ret;
746 }
747
748 - (void *)libVLCMediaPlayer
749 {
750     return instance;
751 }
752 @end
753
754 @implementation VLCMediaPlayer (Private)
755 - (id)initWithDrawable:(id)aDrawable
756 {
757     if (self = [super init])
758     {
759         delegate = nil;
760         media = nil;
761         cachedTime = [[VLCTime nullTime] retain];
762         position = 0.0f;
763         cachedState = VLCMediaPlayerStateStopped;
764
765         // Create a media instance, it doesn't matter what library we start off with
766         // it will change depending on the media descriptor provided to the media
767         // instance
768         libvlc_exception_t ex;
769         libvlc_exception_init( &ex );
770         instance = (void *)libvlc_media_player_new([VLCLibrary sharedInstance], &ex);
771         catch_exception( &ex );
772         
773         [self registerObservers];
774         
775         [self setDrawable:aDrawable];
776     }
777     return self;
778 }
779
780 - (void)registerObservers
781 {
782     libvlc_exception_t ex;
783     libvlc_exception_init( &ex );
784
785     // Attach event observers into the media instance
786     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, &ex );
787     libvlc_event_attach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, &ex );
788     libvlc_event_attach( p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self, &ex );
789     libvlc_event_attach( p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self, &ex );
790     libvlc_event_attach( p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self, &ex );
791     /* FIXME: We may want to turn that off when none is interested by that */
792     libvlc_event_attach( p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged,      self, &ex );
793     libvlc_event_attach( p_em, libvlc_MediaPlayerTimeChanged,     HandleMediaTimeChanged,          self, &ex );
794     catch_exception( &ex );
795 }
796
797 - (void)unregisterObservers
798 {
799     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, NULL );
800     libvlc_event_detach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, NULL );
801     libvlc_event_detach( p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self, NULL );
802     libvlc_event_detach( p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self, NULL );
803     libvlc_event_detach( p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self, NULL );
804     libvlc_event_detach( p_em, libvlc_MediaPlayerPositionChanged,  HandleMediaPositionChanged,      self, NULL );
805     libvlc_event_detach( p_em, libvlc_MediaPlayerTimeChanged,      HandleMediaTimeChanged,          self, NULL );
806 }
807
808 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime
809 {
810     [self willChangeValueForKey:@"time"];
811     [self willChangeValueForKey:@"remainingTime"];
812     [cachedTime release];
813     cachedTime = [[VLCTime timeWithNumber:newTime] retain];
814
815     [self didChangeValueForKey:@"remainingTime"];
816     [self didChangeValueForKey:@"time"];
817 }
818
819 - (void)delaySleep
820 {
821     UpdateSystemActivity(UsrActivity);
822 }
823
824 - (void)mediaPlayerPositionChanged:(NSNumber *)newPosition
825 {
826     // This seems to be the most relevant place to delay sleeping and screen saver.
827     [self delaySleep];
828
829     [self willChangeValueForKey:@"position"];
830     position = [newPosition floatValue];
831     [self didChangeValueForKey:@"position"];
832 }
833
834 - (void)mediaPlayerStateChanged:(NSNumber *)newState
835 {
836     [self willChangeValueForKey:@"state"];
837     cachedState = [newState intValue];
838     [self didChangeValueForKey:@"state"];
839 }
840
841 @end