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