]> git.sesse.net Git - vlc/blob - projects/macosx/framework/Sources/VLCMediaPlayer.m
f48a727ce9818b0251a747b9c841db5be2ad151e
[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, NULL) == 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, NULL);
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_exception_t ex;
256     libvlc_exception_init( &ex );
257     libvlc_media_player_set_nsobject(instance, aDrawable, &ex);
258     catch_exception( &ex );
259 }
260
261 - (id)drawable
262 {
263     libvlc_exception_t ex;
264     libvlc_exception_init( &ex );
265     id ret = libvlc_media_player_get_nsobject(instance);
266     catch_exception( &ex );
267     return ret;
268 }
269
270 - (VLCAudio *)audio
271 {
272     return [[VLCLibrary sharedLibrary] audio];
273 }
274
275 #pragma mark -
276 #pragma mark Subtitles
277
278 - (void)setCurrentVideoSubTitleIndex:(NSUInteger)index
279 {
280     libvlc_exception_t ex;
281     libvlc_exception_init( &ex );
282     libvlc_video_set_spu( instance, (int)index, &ex );
283     catch_exception( &ex );
284 }
285
286 - (NSUInteger)currentVideoSubTitleIndex
287 {
288     libvlc_exception_t ex;
289     libvlc_exception_init( &ex );
290     int count = libvlc_video_get_spu_count( instance, &ex );
291     catch_exception( &ex );
292     if (count <= 0)
293         return NSNotFound;
294     NSUInteger result = libvlc_video_get_spu( instance, &ex );
295     catch_exception( &ex );
296     return result;
297 }
298
299 - (BOOL)openVideoSubTitlesFromFile:(NSString *)path
300 {
301     libvlc_exception_t ex;
302     libvlc_exception_init( &ex );
303     BOOL result = libvlc_video_set_subtitle_file( instance, [path UTF8String], &ex );
304     catch_exception( &ex );
305     return result;
306 }
307
308 - (NSArray *)videoSubTitles
309 {
310     libvlc_exception_t ex;
311     libvlc_exception_init( &ex );
312     int count = libvlc_video_get_spu_count( instance, &ex );
313     catch_exception( &ex );
314
315     libvlc_track_description_t *tracks = libvlc_video_get_spu_description( instance, &ex );
316     NSMutableArray *tempArray = [NSMutableArray array];
317     NSInteger i;
318     for (i = 0; i < count; i++)
319     {
320         [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
321         tracks = tracks->p_next;
322     }
323     return [NSArray arrayWithArray: tempArray];
324 }
325
326
327 #pragma mark -
328 #pragma mark Video Crop geometry
329
330 - (void)setVideoCropGeometry:(char *)value
331 {
332     libvlc_exception_t ex;
333     libvlc_exception_init( &ex );
334     libvlc_video_set_crop_geometry( instance, value, &ex );
335     catch_exception( &ex );
336 }
337
338 - (char *)videoCropGeometry
339 {
340     libvlc_exception_t ex;
341     libvlc_exception_init( &ex );
342     char * result = libvlc_video_get_crop_geometry( instance, &ex );
343     catch_exception( &ex );
344     return result;
345 }
346
347 - (void)setVideoAspectRatio:(char *)value
348 {
349     libvlc_exception_t ex;
350     libvlc_exception_init( &ex );
351     libvlc_video_set_aspect_ratio( instance, value, &ex );
352     catch_exception( &ex );
353 }
354
355 - (char *)videoAspectRatio
356 {
357     libvlc_exception_t ex;
358     libvlc_exception_init( &ex );
359     char * result = libvlc_video_get_aspect_ratio( instance, &ex );
360     catch_exception( &ex );
361     return result;
362 }
363
364 - (void)setVideoTeleText:(int)value
365 {
366     libvlc_exception_t ex;
367     libvlc_exception_init( &ex );
368     libvlc_video_set_teletext( instance, value, &ex );
369     catch_exception( &ex );
370 }
371
372 - (int)videoTeleText
373 {
374     libvlc_exception_t ex;
375     libvlc_exception_init( &ex );
376     int result = libvlc_video_get_teletext( instance, &ex );
377     catch_exception( &ex );
378     return result;
379 }
380
381 - (void)saveVideoSnapshotAt: (NSString *)path withWidth:(NSUInteger)width andHeight:(NSUInteger)height
382 {
383     libvlc_exception_t ex;
384     libvlc_exception_init( &ex );
385     libvlc_video_take_snapshot( instance, [path UTF8String], width, height, &ex );
386     catch_exception( &ex );
387 }
388
389 - (void)setDeinterlaceFilter: (NSString *)name enabled: (BOOL)enabled
390 {
391     libvlc_exception_t ex;
392     libvlc_exception_init( &ex );
393     libvlc_video_set_deinterlace( instance, (int)enabled , [name UTF8String], &ex );
394     catch_exception( &ex );
395 }
396
397 - (void)setRate:(float)value
398 {
399     libvlc_exception_t ex;
400     libvlc_exception_init( &ex );
401     libvlc_media_player_set_rate( instance, value, &ex );
402     catch_exception( &ex );
403 }
404
405 - (float)rate
406 {
407     libvlc_exception_t ex;
408     libvlc_exception_init( &ex );
409     float result = libvlc_media_player_get_rate( instance, &ex );
410     catch_exception( &ex );
411     return result;
412 }
413
414 - (NSSize)videoSize
415 {
416     libvlc_exception_t ex;
417     libvlc_exception_init( &ex );
418     NSSize result = NSMakeSize(libvlc_video_get_height((libvlc_media_player_t *)instance, &ex),
419                                libvlc_video_get_width((libvlc_media_player_t *)instance, &ex));
420     catch_exception( &ex );
421     return result;
422 }
423
424 - (BOOL)hasVideoOut
425 {
426     libvlc_exception_t ex;
427     libvlc_exception_init( &ex );
428     BOOL result = libvlc_media_player_has_vout((libvlc_media_player_t *)instance, &ex);
429     if (libvlc_exception_raised( &ex ))
430     {
431         libvlc_exception_clear( &ex );
432         return NO;
433     }
434     else
435         return result;
436 }
437
438 - (float)framesPerSecond
439 {
440     libvlc_exception_t ex;
441     libvlc_exception_init( &ex );
442     float result = libvlc_media_player_get_fps( (libvlc_media_player_t *)instance, &ex );
443     catch_exception( &ex );
444     return result;
445 }
446
447 - (void)setTime:(VLCTime *)value
448 {
449     libvlc_exception_t ex;
450     libvlc_exception_init( &ex );
451     // Time is managed in seconds, while duration is managed in microseconds
452     // TODO: Redo VLCTime to provide value numberAsMilliseconds, numberAsMicroseconds, numberAsSeconds, numberAsMinutes, numberAsHours
453     libvlc_media_player_set_time( (libvlc_media_player_t *)instance, 
454                                     (value ? [[value numberValue] longLongValue] / 1000 : 0),
455                                     &ex );
456     catch_exception( &ex );
457 }
458
459 - (VLCTime *)time
460 {
461     return cachedTime;
462 }
463
464 - (VLCTime *)remainingTime
465 {
466     return cachedRemainingTime;
467 }
468
469 - (int)fps
470 {
471     libvlc_exception_t ex;
472     libvlc_exception_init( &ex );
473     int result = libvlc_media_player_get_fps( instance, &ex );
474     catch_exception( &ex );
475     return result;
476 }
477
478 #pragma mark -
479 #pragma mark Chapters
480 - (void)setCurrentChapterIndex:(NSUInteger)value;
481 {
482     libvlc_exception_t ex;
483     libvlc_exception_init( &ex );
484     libvlc_media_player_set_chapter( instance, value, &ex );
485     catch_exception( &ex );
486 }
487
488 - (NSUInteger)currentChapterIndex
489 {
490     libvlc_exception_t ex;
491     libvlc_exception_init( &ex );
492     int count = libvlc_media_player_get_chapter_count( instance, &ex );
493     catch_exception( &ex );
494     if (count <= 0)
495         return NSNotFound;
496     NSUInteger result = libvlc_media_player_get_chapter( instance, &ex );
497     catch_exception( &ex );
498     return result;
499 }
500
501 - (void)nextChapter
502 {
503     libvlc_exception_t ex;
504     libvlc_exception_init( &ex );
505     libvlc_media_player_next_chapter( instance, &ex );
506     catch_exception( &ex );
507 }
508
509 - (void)previousChapter
510 {
511     libvlc_exception_t ex;
512     libvlc_exception_init( &ex );
513     libvlc_media_player_previous_chapter( instance, &ex );
514     catch_exception( &ex );
515 }
516
517 - (NSArray *)chaptersForTitleIndex:(NSUInteger)title
518 {
519     libvlc_exception_t ex;
520     libvlc_exception_init( &ex );
521     int count = libvlc_media_player_get_chapter_count(instance, &ex);
522     if (count <= 0)
523         return [NSArray array];
524
525     libvlc_track_description_t *tracks = libvlc_video_get_chapter_description( instance, title, &ex );
526     NSMutableArray *tempArray = [NSMutableArray array];
527     NSInteger i;
528     for (i = 0; i < count ; i++)
529     {
530         [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
531         tracks = tracks->p_next;
532     }
533     return [NSArray arrayWithArray: tempArray];
534 }
535
536 #pragma mark -
537 #pragma mark Titles
538
539 - (void)setCurrentTitleIndex:(NSUInteger)value
540 {
541     libvlc_exception_t ex;
542     libvlc_exception_init( &ex );    
543     libvlc_media_player_set_title( instance, value, &ex );
544     catch_exception( &ex );
545 }
546
547 - (NSUInteger)currentTitleIndex
548 {
549     libvlc_exception_t ex;
550     libvlc_exception_init( &ex );
551
552     int count = libvlc_media_player_get_title_count( instance, &ex );
553     catch_exception( &ex );
554     if (count <= 0)
555         return NSNotFound;
556     
557     NSUInteger result = libvlc_media_player_get_title( instance, &ex );
558     catch_exception( &ex );
559     return result;
560 }
561
562 - (int)countOfTitles
563 {
564     libvlc_exception_t ex;
565     libvlc_exception_init( &ex );
566     int result = libvlc_media_player_get_title_count( instance, &ex );
567     catch_exception( &ex );
568     return result;
569 }
570
571 - (NSArray *)titles
572 {
573     libvlc_exception_t ex;
574     libvlc_exception_init( &ex );
575     libvlc_track_description_t *tracks = libvlc_video_get_title_description( instance, &ex );
576     NSMutableArray *tempArray = [NSMutableArray array];
577     NSInteger i;
578     for (i = 0; i < [self countOfTitles] ; i++)
579     {
580         [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
581         tracks = tracks->p_next;
582     }
583     return [NSArray arrayWithArray: tempArray];
584 }
585
586 #pragma mark -
587 #pragma mark Audio tracks
588 - (void)setCurrentAudioTrackIndex:(NSUInteger)value
589 {
590     libvlc_exception_t ex;
591     libvlc_exception_init( &ex );
592     libvlc_audio_set_track( instance, (int)value, &ex );
593     catch_exception( &ex );
594 }
595
596 - (NSUInteger)currentAudioTrackIndex
597 {
598     libvlc_exception_t ex;
599     libvlc_exception_init( &ex );
600     int count = libvlc_audio_get_track_count( instance, &ex );
601     catch_exception( &ex );
602     if (count <= 0)
603         return NSNotFound;
604     
605     NSUInteger result = libvlc_audio_get_track( instance, &ex );
606     catch_exception( &ex );
607     return result;
608 }
609
610 - (NSArray *)audioTracks
611 {
612     libvlc_exception_t ex;
613     libvlc_exception_init( &ex );
614     int count = libvlc_audio_get_track_count( instance, &ex );
615     catch_exception( &ex );
616     if (count <= 0)
617         return [NSArray array];
618
619     libvlc_track_description_t *tracks = libvlc_audio_get_track_description( instance, &ex );
620     NSMutableArray *tempArray = [NSMutableArray array];
621     NSInteger i;
622     for (i = 0; i < count ; i++)
623     {
624         [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
625         tracks = tracks->p_next;
626     }
627
628     return [NSArray arrayWithArray: tempArray];
629 }
630
631 - (void)setAudioChannel:(int)value
632 {
633     libvlc_exception_t ex;
634     libvlc_exception_init( &ex );
635     libvlc_audio_set_channel( instance, value, &ex );
636     catch_exception( &ex );
637 }
638
639 - (int)audioChannel
640 {
641     libvlc_exception_t ex;
642     libvlc_exception_init( &ex );
643     int result = libvlc_audio_get_channel( instance, &ex );
644     catch_exception( &ex );
645     return result;
646 }
647
648 - (void)setMedia:(VLCMedia *)value
649 {
650     if (media != value)
651     {
652         if (media && [media compare:value] == NSOrderedSame)
653             return;
654         
655         [media release];
656         media = [value retain];
657
658         libvlc_exception_t ex;
659         libvlc_exception_init( &ex );
660         libvlc_media_player_set_media( instance, [media libVLCMediaDescriptor], &ex );
661         catch_exception( &ex );
662     }
663 }
664
665 - (VLCMedia *)media
666 {
667     return media;
668 }
669
670 - (BOOL)play
671 {    
672     libvlc_exception_t ex;
673     libvlc_exception_init( &ex );
674     libvlc_media_player_play( (libvlc_media_player_t *)instance, &ex );
675     catch_exception( &ex );
676     return YES;
677 }
678
679 - (void)pause
680 {
681     if( [NSThread isMainThread] )
682     {
683         /* Hack because we create a dead lock here, when the vout is stopped
684          * and tries to recontact us on the main thread */
685         /* FIXME: to do this properly we need to do some locking. We may want 
686          * to move that to libvlc */
687         [self performSelectorInBackground:@selector(pause) withObject:nil];
688         return;
689     }
690
691     // Pause the stream
692     libvlc_exception_t ex;
693     libvlc_exception_init( &ex );
694     libvlc_media_player_pause( (libvlc_media_player_t *)instance, &ex );
695
696     // fail gracefully
697     // in most cases, it's just EOF so let's stop
698     if (libvlc_exception_raised(&ex))
699         [self stop];
700
701     libvlc_exception_clear(&ex);
702 }
703
704 - (void)stop
705 {
706     libvlc_exception_t ex;
707     libvlc_exception_init( &ex );
708     libvlc_media_player_stop((libvlc_media_player_t *)instance, &ex);
709     catch_exception( &ex );
710 }
711
712 - (void)fastForward
713 {
714     [self fastForwardAtRate: 2.0];
715 }
716
717 - (void)fastForwardAtRate:(float)rate
718 {
719     [self setRate:rate];
720 }
721
722 - (void)rewind
723 {
724     [self rewindAtRate: 2.0];
725 }
726
727 - (void)rewindAtRate:(float)rate
728 {
729     [self setRate: -rate];
730 }
731
732 - (void)jumpBackward:(NSInteger)interval
733 {
734     if( [self isSeekable] )
735     {
736         interval = interval * 1000000;
737         [self setTime: [VLCTime timeWithInt: ([[self time] intValue] - interval)]];
738     }
739 }
740
741 - (void)jumpForward:(NSInteger)interval
742 {
743     if( [self isSeekable] )
744     {
745         interval = interval * 1000000;
746         [self setTime: [VLCTime timeWithInt: ([[self time] intValue] + interval)]];
747     }
748 }
749
750 - (void)extraShortJumpBackward
751 {
752     [self jumpBackward:3];
753 }
754
755 - (void)extraShortJumpForward
756 {
757     [self jumpForward:3];
758 }
759
760 - (void)shortJumpBackward
761 {
762     [self jumpBackward:10];
763 }
764
765 - (void)shortJumpForward
766 {
767     [self jumpForward:10];
768 }
769
770 - (void)mediumJumpBackward
771 {
772     [self jumpBackward:60];
773 }
774
775 - (void)mediumJumpForward
776 {
777     [self jumpForward:60];
778 }
779
780 - (void)longJumpBackward
781 {
782     [self jumpBackward:300];
783 }
784
785 - (void)longJumpForward
786 {
787     [self jumpForward:300];
788 }
789
790 + (NSSet *)keyPathsForValuesAffectingIsPlaying
791 {
792     return [NSSet setWithObjects:@"state", nil];
793 }
794
795 - (BOOL)isPlaying
796 {
797     VLCMediaPlayerState state = [self state];
798     return ((state == VLCMediaPlayerStateOpening) || (state == VLCMediaPlayerStateBuffering) ||
799             (state == VLCMediaPlayerStatePlaying));
800 }
801
802 - (BOOL)willPlay
803 {
804     libvlc_exception_t ex;
805     libvlc_exception_init( &ex );
806     BOOL ret = libvlc_media_player_will_play( (libvlc_media_player_t *)instance, &ex );
807     if (libvlc_exception_raised(&ex))
808     {
809         libvlc_exception_clear(&ex);
810         return NO;
811     }
812     else
813         return ret;
814 }
815
816 static const VLCMediaPlayerState libvlc_to_local_state[] =
817 {
818     [libvlc_Stopped]    = VLCMediaPlayerStateStopped,
819     [libvlc_Opening]    = VLCMediaPlayerStateOpening,
820     [libvlc_Buffering]  = VLCMediaPlayerStateBuffering,
821     [libvlc_Playing]    = VLCMediaPlayerStatePlaying,
822     [libvlc_Paused]     = VLCMediaPlayerStatePaused,
823     [libvlc_Ended]      = VLCMediaPlayerStateEnded,
824     [libvlc_Error]      = VLCMediaPlayerStateError
825 };
826
827 - (VLCMediaPlayerState)state
828 {
829     return cachedState;
830 }
831
832 - (float)position
833 {
834     return position;
835 }
836
837 - (void)setPosition:(float)newPosition
838 {
839     libvlc_exception_t ex;
840     libvlc_exception_init( &ex );
841     libvlc_media_player_set_position( instance, newPosition, &ex );
842     catch_exception( &ex );
843 }
844
845 - (BOOL)isSeekable
846 {
847     libvlc_exception_t ex;
848     libvlc_exception_init( &ex );
849     BOOL ret = libvlc_media_player_is_seekable( instance, &ex );
850     catch_exception( &ex );
851     return ret;
852 }
853
854 - (BOOL)canPause
855 {
856     libvlc_exception_t ex;
857     libvlc_exception_init( &ex );
858     BOOL ret = libvlc_media_player_can_pause( instance, &ex );
859     catch_exception( &ex );
860     return ret;
861 }
862
863 - (void *)libVLCMediaPlayer
864 {
865     return instance;
866 }
867 @end
868
869 @implementation VLCMediaPlayer (Private)
870 - (id)initWithDrawable:(id)aDrawable
871 {
872     if (self = [super init])
873     {
874         delegate = nil;
875         media = nil;
876         cachedTime = [[VLCTime nullTime] retain];
877         cachedRemainingTime = [[VLCTime nullTime] retain];
878         position = 0.0f;
879         cachedState = VLCMediaPlayerStateStopped;
880
881         // Create a media instance, it doesn't matter what library we start off with
882         // it will change depending on the media descriptor provided to the media
883         // instance
884         libvlc_exception_t ex;
885         libvlc_exception_init( &ex );
886         instance = (void *)libvlc_media_player_new([VLCLibrary sharedInstance], &ex);
887         catch_exception( &ex );
888         
889         [self registerObservers];
890         
891         [self setDrawable:aDrawable];
892     }
893     return self;
894 }
895
896 - (void)registerObservers
897 {
898     libvlc_exception_t ex;
899     libvlc_exception_init( &ex );
900
901     // Attach event observers into the media instance
902     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, &ex );
903     libvlc_event_attach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, &ex );
904     libvlc_event_attach( p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self, &ex );
905     libvlc_event_attach( p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self, &ex );
906     libvlc_event_attach( p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self, &ex );
907     /* FIXME: We may want to turn that off when none is interested by that */
908     libvlc_event_attach( p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged,      self, &ex );
909     libvlc_event_attach( p_em, libvlc_MediaPlayerTimeChanged,     HandleMediaTimeChanged,          self, &ex );
910     libvlc_event_attach( p_em, libvlc_MediaPlayerMediaChanged,     HandleMediaPlayerMediaChanged,  self, &ex );
911     catch_exception( &ex );
912 }
913
914 - (void)unregisterObservers
915 {
916     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, NULL );
917     libvlc_event_detach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, NULL );
918     libvlc_event_detach( p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self, NULL );
919     libvlc_event_detach( p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self, NULL );
920     libvlc_event_detach( p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self, NULL );
921     libvlc_event_detach( p_em, libvlc_MediaPlayerPositionChanged,  HandleMediaPositionChanged,      self, NULL );
922     libvlc_event_detach( p_em, libvlc_MediaPlayerTimeChanged,      HandleMediaTimeChanged,          self, NULL );
923     libvlc_event_attach( p_em, libvlc_MediaPlayerMediaChanged,     HandleMediaPlayerMediaChanged,   self, NULL );
924 }
925
926 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime
927 {
928     [self willChangeValueForKey:@"time"];
929     [self willChangeValueForKey:@"remainingTime"];
930     [cachedTime release];
931     cachedTime = [[VLCTime timeWithNumber:newTime] retain];
932     [cachedRemainingTime release];
933     double currentTime = [[cachedTime numberValue] doubleValue];
934     double remaining = currentTime / position * (1 - position);
935     cachedRemainingTime = [[VLCTime timeWithNumber:[NSNumber numberWithDouble:-remaining]] retain];
936     [self didChangeValueForKey:@"remainingTime"];
937     [self didChangeValueForKey:@"time"];
938 }
939
940 - (void)delaySleep
941 {
942     UpdateSystemActivity(UsrActivity);
943 }
944
945 - (void)mediaPlayerPositionChanged:(NSNumber *)newPosition
946 {
947     // This seems to be the most relevant place to delay sleeping and screen saver.
948     [self delaySleep];
949
950     [self willChangeValueForKey:@"position"];
951     position = [newPosition floatValue];
952     [self didChangeValueForKey:@"position"];
953 }
954
955 - (void)mediaPlayerStateChanged:(NSNumber *)newState
956 {
957     [self willChangeValueForKey:@"state"];
958     cachedState = [newState intValue];
959     [self didChangeValueForKey:@"state"];
960 }
961
962 - (void)mediaPlayerMediaChanged:(VLCMedia *)newMedia
963 {
964     [self willChangeValueForKey:@"media"];
965     if (media != newMedia)
966     {
967         [media release];
968         media = [newMedia retain];
969     }
970     [self didChangeValueForKey:@"media"];
971 }
972
973 @end