]> git.sesse.net Git - vlc/blob - projects/macosx/framework/Sources/VLCMediaPlayer.m
6b409cc9adfed2e9571109e55413c21d43b6ea78
[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 static void HandleMediaPlayerMediaChanged(const libvlc_event_t * event, void * self)
128 {
129     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
130
131     [[VLCEventManager sharedManager] callOnMainThreadObject:self
132                                                  withMethod:@selector(mediaPlayerMediaChanged:)
133                                        withArgumentAsObject:[VLCMedia mediaWithLibVLCMediaDescriptor:event->u.media_player_media_changed.new_media]];
134
135     [pool release];
136
137 }
138
139
140 // TODO: Documentation
141 @interface VLCMediaPlayer (Private)
142 - (id)initWithDrawable:(id)aDrawable;
143
144 - (void)registerObservers;
145 - (void)unregisterObservers;
146 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime;
147 - (void)mediaPlayerPositionChanged:(NSNumber *)newTime;
148 - (void)mediaPlayerStateChanged:(NSNumber *)newState;
149 - (void)mediaPlayerMediaChanged:(VLCMedia *)media;
150 @end
151
152 @implementation VLCMediaPlayer
153
154 /* Bindings */
155 + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
156 {
157     static NSDictionary * dict = nil;
158     NSSet * superKeyPaths;
159     if( !dict )
160     {
161         dict = [[NSDictionary dictionaryWithObjectsAndKeys:
162             [NSSet setWithObject:@"state"], @"playing",
163             [NSSet setWithObjects:@"state", @"media", nil], @"seekable",
164             [NSSet setWithObjects:@"state", @"media", nil], @"canPause",
165             [NSSet setWithObjects:@"state", @"media", nil], @"description",
166             nil] retain];
167     }
168     if( (superKeyPaths = [super keyPathsForValuesAffectingValueForKey: key]) )
169     {
170         NSMutableSet * ret = [NSMutableSet setWithSet:[dict objectForKey: key]];
171         [ret unionSet:superKeyPaths];
172         return ret;
173     }
174     return [dict objectForKey: key];
175 }
176
177 /* Contructor */
178 - (id)init
179 {
180     return [self initWithDrawable:nil];
181 }
182
183 - (id)initWithVideoView:(VLCVideoView *)aVideoView
184 {
185     return [self initWithDrawable: aVideoView];
186 }
187
188 - (id)initWithVideoLayer:(VLCVideoLayer *)aVideoLayer
189 {
190     return [self initWithDrawable: aVideoLayer];
191 }
192
193 - (void)release
194 {
195     @synchronized(self)
196     {
197         if([self retainCount] <= 1)
198         {
199             /* We must make sure we won't receive new event after an upcoming dealloc
200              * We also may receive a -retain in some event callback that may occcur
201              * Before libvlc_event_detach. So this can't happen in dealloc */
202             [self unregisterObservers];
203         }
204         [super release];
205     }
206 }
207
208 - (void)dealloc
209 {
210     NSAssert(libvlc_media_player_get_state(instance) == libvlc_Stopped, @"You released the media player before ensuring that it is stopped");
211
212     // Always get rid of the delegate first so we can stop sending messages to it
213     // TODO: Should we tell the delegate that we're shutting down?
214     delegate = nil;
215
216     // Clear our drawable as we are going to release it, we don't
217     // want the core to use it from this point. This won't happen as
218     // the media player must be stopped.
219     libvlc_media_player_set_nsobject(instance, nil);
220
221     libvlc_media_player_release(instance);
222
223     // Get rid of everything else
224     [media release];
225     [cachedTime release];
226     [cachedRemainingTime release];
227     [drawable release];
228
229     [super dealloc];
230 }
231
232 - (void)setDelegate:(id)value
233 {
234     delegate = value;
235 }
236
237 - (id)delegate
238 {
239     return delegate;
240 }
241
242 - (void)setVideoView:(VLCVideoView *)aVideoView
243 {
244     [self setDrawable: aVideoView];
245 }
246
247 - (void)setVideoLayer:(VLCVideoLayer *)aVideoLayer
248 {
249     [self setDrawable: aVideoLayer];
250 }
251
252 - (void)setDrawable:(id)aDrawable
253 {
254     // Make sure that this instance has been associated with the drawing canvas.
255     libvlc_media_player_set_nsobject(instance, aDrawable);
256 }
257
258 - (id)drawable
259 {
260     return libvlc_media_player_get_nsobject(instance);
261 }
262
263 - (VLCAudio *)audio
264 {
265     return [[VLCLibrary sharedLibrary] audio];
266 }
267
268 #pragma mark -
269 #pragma mark Subtitles
270
271 - (void)setCurrentVideoSubTitleIndex:(NSUInteger)index
272 {
273     libvlc_video_set_spu( instance, (int)index );
274 }
275
276 - (NSUInteger)currentVideoSubTitleIndex
277 {
278     NSInteger count = libvlc_video_get_spu_count(instance);
279
280     if (count <= 0)
281         return NSNotFound;
282
283         return libvlc_video_get_spu(instance);
284 }
285
286 - (BOOL)openVideoSubTitlesFromFile:(NSString *)path
287 {
288     return libvlc_video_set_subtitle_file(instance, [path UTF8String]);
289 }
290
291 - (NSArray *)videoSubTitles
292 {
293     libvlc_track_description_t *currentTrack = libvlc_video_get_spu_description(instance);
294
295     NSMutableArray *tempArray = [NSMutableArray array];
296     while (currentTrack) {
297         [tempArray addObject:[NSString stringWithUTF8String:currentTrack->psz_name]];
298         currentTrack = currentTrack->p_next;
299     }
300     libvlc_track_description_release(currentTrack);
301     return [NSArray arrayWithArray: tempArray];
302 }
303
304
305 #pragma mark -
306 #pragma mark Video Crop geometry
307
308 - (void)setVideoCropGeometry:(char *)value
309 {
310     libvlc_video_set_crop_geometry( instance, value );
311 }
312
313 - (char *)videoCropGeometry
314 {
315     char * result = libvlc_video_get_crop_geometry( instance );
316     return result;
317 }
318
319 - (void)setVideoAspectRatio:(char *)value
320 {
321     libvlc_video_set_aspect_ratio( instance, value );
322 }
323
324 - (char *)videoAspectRatio
325 {
326     char * result = libvlc_video_get_aspect_ratio( instance );
327     return result;
328 }
329
330 - (void)saveVideoSnapshotAt: (NSString *)path withWidth:(NSUInteger)width andHeight:(NSUInteger)height
331 {
332         libvlc_exception_t ex;
333     libvlc_exception_init( &ex );
334     libvlc_video_take_snapshot( instance, [path UTF8String], width, height, &ex );
335         catch_exception( &ex );
336 }
337
338 - (void)setDeinterlaceFilter: (NSString *)name
339 {
340     libvlc_video_set_deinterlace( instance, [name UTF8String] );
341 }
342
343 - (void)setRate:(float)value
344 {
345     libvlc_media_player_set_rate(instance, value);
346 }
347
348 - (float)rate
349 {
350     return libvlc_media_player_get_rate(instance);
351 }
352
353 - (NSSize)videoSize
354 {
355     NSSize result = NSMakeSize(libvlc_video_get_height((libvlc_media_player_t *)instance),
356                                libvlc_video_get_width((libvlc_media_player_t *)instance));
357     return result;
358 }
359
360 - (BOOL)hasVideoOut
361 {
362     return libvlc_media_player_has_vout(instance);
363 }
364
365 - (float)framesPerSecond
366 {
367     return libvlc_media_player_get_fps(instance);
368 }
369
370 - (void)setTime:(VLCTime *)value
371 {
372     // Time is managed in seconds, while duration is managed in microseconds
373     // TODO: Redo VLCTime to provide value numberAsMilliseconds, numberAsMicroseconds, numberAsSeconds, numberAsMinutes, numberAsHours
374     libvlc_media_player_set_time(instance, value ? [[value numberValue] longLongValue] : 0);
375 }
376
377 - (VLCTime *)time
378 {
379     return cachedTime;
380 }
381
382 - (VLCTime *)remainingTime
383 {
384     return cachedRemainingTime;
385 }
386
387 - (NSUInteger)fps
388 {
389     return libvlc_media_player_get_fps(instance);
390 }
391
392 #pragma mark -
393 #pragma mark Chapters
394 - (void)setCurrentChapterIndex:(NSUInteger)value;
395 {
396     libvlc_media_player_set_chapter(instance, value);
397 }
398
399 - (NSUInteger)currentChapterIndex
400 {
401     NSInteger count = libvlc_media_player_get_chapter_count(instance);
402     if (count <= 0)
403         return NSNotFound;
404     NSUInteger result = libvlc_media_player_get_chapter(instance);
405     return result;
406 }
407
408 - (void)nextChapter
409 {
410     libvlc_media_player_next_chapter(instance);
411 }
412
413 - (void)previousChapter
414 {
415     libvlc_media_player_previous_chapter(instance);
416 }
417
418 - (NSArray *)chaptersForTitleIndex:(NSUInteger)title
419 {
420     NSInteger count = libvlc_media_player_get_chapter_count(instance);
421     if (count <= 0)
422         return [NSArray array];
423
424     libvlc_track_description_t *tracks = libvlc_video_get_chapter_description(instance, title);
425     NSMutableArray *tempArray = [NSMutableArray array];
426     NSInteger i;
427     for (i = 0; i < count ; i++)
428     {
429         [tempArray addObject:[NSString stringWithUTF8String:tracks->psz_name]];
430         tracks = tracks->p_next;
431     }
432     libvlc_track_description_release(tracks);
433     return [NSArray arrayWithArray:tempArray];
434 }
435
436 #pragma mark -
437 #pragma mark Titles
438
439 - (void)setCurrentTitleIndex:(NSUInteger)value
440 {
441     libvlc_media_player_set_title(instance, value);
442 }
443
444 - (NSUInteger)currentTitleIndex
445 {
446     NSInteger count = libvlc_media_player_get_title_count(instance);
447     if (count <= 0)
448         return NSNotFound;
449
450     return libvlc_media_player_get_title(instance);
451 }
452
453 - (NSUInteger)countOfTitles
454 {
455     NSUInteger result = libvlc_media_player_get_title_count(instance);
456     return result;
457 }
458
459 - (NSArray *)titles
460 {
461     libvlc_track_description_t *tracks = libvlc_video_get_title_description(instance);
462     NSMutableArray *tempArray = [NSMutableArray array];
463     NSInteger i;
464     for (i = 0; i < [self countOfTitles] ; i++)
465     {
466         [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
467         tracks = tracks->p_next;
468     }
469     libvlc_track_description_release(tracks);
470     return [NSArray arrayWithArray: tempArray];
471 }
472
473 #pragma mark -
474 #pragma mark Audio tracks
475 - (void)setCurrentAudioTrackIndex:(NSUInteger)value
476 {
477     libvlc_audio_set_track( instance, (int)value);
478 }
479
480 - (NSUInteger)currentAudioTrackIndex
481 {
482     NSInteger count = libvlc_audio_get_track_count(instance);
483     if (count <= 0)
484         return NSNotFound;
485
486     NSUInteger result = libvlc_audio_get_track(instance);
487     return result;
488 }
489
490 - (NSArray *)audioTracks
491 {
492     NSInteger count = libvlc_audio_get_track_count(instance);
493     if (count <= 0)
494         return [NSArray array];
495
496     libvlc_track_description_t *tracks = libvlc_audio_get_track_description(instance);
497     NSMutableArray *tempArray = [NSMutableArray array];
498     NSUInteger i;
499     for (i = 0; i < count ; i++)
500     {
501         [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
502         tracks = tracks->p_next;
503     }
504     libvlc_track_description_release(tracks);
505
506     return [NSArray arrayWithArray: tempArray];
507 }
508
509 - (void)setAudioChannel:(NSInteger)value
510 {
511     libvlc_audio_set_channel(instance, value);
512 }
513
514 - (NSInteger)audioChannel
515 {
516     return libvlc_audio_get_channel(instance);
517 }
518
519 - (void)setMedia:(VLCMedia *)value
520 {
521     if (media != value)
522     {
523         if (media && [media compare:value] == NSOrderedSame)
524             return;
525
526         [media release];
527         media = [value retain];
528
529         libvlc_media_player_set_media(instance, [media libVLCMediaDescriptor]);
530     }
531 }
532
533 - (VLCMedia *)media
534 {
535     return media;
536 }
537
538 - (BOOL)play
539 {
540     libvlc_media_player_play(instance);
541     return YES;
542 }
543
544 - (void)pause
545 {
546     if( [NSThread isMainThread] )
547     {
548         /* Hack because we create a dead lock here, when the vout is stopped
549          * and tries to recontact us on the main thread */
550         /* FIXME: to do this properly we need to do some locking. We may want
551          * to move that to libvlc */
552         [self performSelectorInBackground:@selector(pause) withObject:nil];
553         return;
554     }
555
556     // Pause the stream
557     libvlc_media_player_pause(instance);
558 }
559
560 - (void)stop
561 {
562     libvlc_media_player_stop(instance);
563 }
564
565 - (void)gotoNextFrame
566 {
567     libvlc_media_player_next_frame(instance);
568
569 }
570
571 - (void)fastForward
572 {
573     [self fastForwardAtRate: 2.0];
574 }
575
576 - (void)fastForwardAtRate:(float)rate
577 {
578     [self setRate:rate];
579 }
580
581 - (void)rewind
582 {
583     [self rewindAtRate: 2.0];
584 }
585
586 - (void)rewindAtRate:(float)rate
587 {
588     [self setRate: -rate];
589 }
590
591 - (void)jumpBackward:(NSInteger)interval
592 {
593     if( [self isSeekable] )
594     {
595         interval = interval * 1000;
596         [self setTime: [VLCTime timeWithInt: ([[self time] intValue] - interval)]];
597     }
598 }
599
600 - (void)jumpForward:(NSInteger)interval
601 {
602     if( [self isSeekable] )
603     {
604         interval = interval * 1000;
605         [self setTime: [VLCTime timeWithInt: ([[self time] intValue] + interval)]];
606     }
607 }
608
609 - (void)extraShortJumpBackward
610 {
611     [self jumpBackward:3];
612 }
613
614 - (void)extraShortJumpForward
615 {
616     [self jumpForward:3];
617 }
618
619 - (void)shortJumpBackward
620 {
621     [self jumpBackward:10];
622 }
623
624 - (void)shortJumpForward
625 {
626     [self jumpForward:10];
627 }
628
629 - (void)mediumJumpBackward
630 {
631     [self jumpBackward:60];
632 }
633
634 - (void)mediumJumpForward
635 {
636     [self jumpForward:60];
637 }
638
639 - (void)longJumpBackward
640 {
641     [self jumpBackward:300];
642 }
643
644 - (void)longJumpForward
645 {
646     [self jumpForward:300];
647 }
648
649 + (NSSet *)keyPathsForValuesAffectingIsPlaying
650 {
651     return [NSSet setWithObjects:@"state", nil];
652 }
653
654 - (BOOL)isPlaying
655 {
656     VLCMediaPlayerState state = [self state];
657     return ((state == VLCMediaPlayerStateOpening) || (state == VLCMediaPlayerStateBuffering) ||
658             (state == VLCMediaPlayerStatePlaying));
659 }
660
661 - (BOOL)willPlay
662 {
663     return libvlc_media_player_will_play(instance);
664 }
665
666 static const VLCMediaPlayerState libvlc_to_local_state[] =
667 {
668     [libvlc_Stopped]    = VLCMediaPlayerStateStopped,
669     [libvlc_Opening]    = VLCMediaPlayerStateOpening,
670     [libvlc_Buffering]  = VLCMediaPlayerStateBuffering,
671     [libvlc_Playing]    = VLCMediaPlayerStatePlaying,
672     [libvlc_Paused]     = VLCMediaPlayerStatePaused,
673     [libvlc_Ended]      = VLCMediaPlayerStateEnded,
674     [libvlc_Error]      = VLCMediaPlayerStateError
675 };
676
677 - (VLCMediaPlayerState)state
678 {
679     return cachedState;
680 }
681
682 - (float)position
683 {
684     return position;
685 }
686
687 - (void)setPosition:(float)newPosition
688 {
689     libvlc_media_player_set_position(instance, newPosition);
690 }
691
692 - (BOOL)isSeekable
693 {
694     return libvlc_media_player_is_seekable(instance);
695 }
696
697 - (BOOL)canPause
698 {
699     return libvlc_media_player_can_pause(instance);
700 }
701
702 - (void *)libVLCMediaPlayer
703 {
704     return instance;
705 }
706 @end
707
708 @implementation VLCMediaPlayer (Private)
709 - (id)initWithDrawable:(id)aDrawable
710 {
711     if (self = [super init])
712     {
713         delegate = nil;
714         media = nil;
715         cachedTime = [[VLCTime nullTime] retain];
716         cachedRemainingTime = [[VLCTime nullTime] retain];
717         position = 0.0f;
718         cachedState = VLCMediaPlayerStateStopped;
719
720         // Create a media instance, it doesn't matter what library we start off with
721         // it will change depending on the media descriptor provided to the media
722         // instance
723         libvlc_exception_t ex;
724         libvlc_exception_init( &ex );
725         instance = libvlc_media_player_new([VLCLibrary sharedInstance]);
726         catch_exception( &ex );
727
728         [self registerObservers];
729
730         [self setDrawable:aDrawable];
731     }
732     return self;
733 }
734
735 - (void)registerObservers
736 {
737     // Attach event observers into the media instance
738     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager(instance);
739     libvlc_event_attach(p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self);
740     libvlc_event_attach(p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self);
741     libvlc_event_attach(p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self);
742     libvlc_event_attach(p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self);
743     /* FIXME: We may want to turn that off when none is interested by that */
744     libvlc_event_attach(p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged,      self);
745     libvlc_event_attach(p_em, libvlc_MediaPlayerTimeChanged,     HandleMediaTimeChanged,          self);
746     libvlc_event_attach(p_em, libvlc_MediaPlayerMediaChanged,    HandleMediaPlayerMediaChanged,  self);
747 }
748
749 - (void)unregisterObservers
750 {
751     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager(instance);
752     libvlc_event_detach(p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self);
753     libvlc_event_detach(p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self);
754     libvlc_event_detach(p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self);
755     libvlc_event_detach(p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self);
756     libvlc_event_detach(p_em, libvlc_MediaPlayerPositionChanged,  HandleMediaPositionChanged,      self);
757     libvlc_event_detach(p_em, libvlc_MediaPlayerTimeChanged,      HandleMediaTimeChanged,          self);
758     libvlc_event_detach(p_em, libvlc_MediaPlayerMediaChanged,     HandleMediaPlayerMediaChanged,   self);
759 }
760
761 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime
762 {
763     [self willChangeValueForKey:@"time"];
764     [self willChangeValueForKey:@"remainingTime"];
765     [cachedTime release];
766     cachedTime = [[VLCTime timeWithNumber:newTime] retain];
767     [cachedRemainingTime release];
768     double currentTime = [[cachedTime numberValue] doubleValue];
769     double remaining = currentTime / position * (1 - position);
770     cachedRemainingTime = [[VLCTime timeWithNumber:[NSNumber numberWithDouble:-remaining]] retain];
771     [self didChangeValueForKey:@"remainingTime"];
772     [self didChangeValueForKey:@"time"];
773 }
774
775 - (void)delaySleep
776 {
777     UpdateSystemActivity(UsrActivity);
778 }
779
780 - (void)mediaPlayerPositionChanged:(NSNumber *)newPosition
781 {
782     // This seems to be the most relevant place to delay sleeping and screen saver.
783     [self delaySleep];
784
785     [self willChangeValueForKey:@"position"];
786     position = [newPosition floatValue];
787     [self didChangeValueForKey:@"position"];
788 }
789
790 - (void)mediaPlayerStateChanged:(NSNumber *)newState
791 {
792     [self willChangeValueForKey:@"state"];
793     cachedState = [newState intValue];
794     [self didChangeValueForKey:@"state"];
795 }
796
797 - (void)mediaPlayerMediaChanged:(VLCMedia *)newMedia
798 {
799     [self willChangeValueForKey:@"media"];
800     if (media != newMedia)
801     {
802         [media release];
803         media = [newMedia retain];
804     }
805     [self didChangeValueForKey:@"media"];
806 }
807
808 @end