]> git.sesse.net Git - vlc/blob - projects/macosx/framework/Sources/VLCMediaPlayer.m
Make sure we don't use the deprecated get_drawable(), by using get_nsobject().
[vlc] / projects / macosx / framework / Sources / VLCMediaPlayer.m
1 /*****************************************************************************
2  * VLCMediaPlayer.m: VLCKit.framework VLCMediaPlayer implementation
3  *****************************************************************************
4  * Copyright (C) 2007 Pierre d'Herbemont
5  * Copyright (C) 2007 the VideoLAN team
6  * $Id$
7  *
8  * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
9  *          Faustion Osuna <enrique.osuna # gmail.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #import "VLCLibrary.h"
27 #import "VLCMediaPlayer.h"
28 #import "VLCEventManager.h"
29 #import "VLCLibVLCBridging.h"
30 #import "VLCVideoView.h"
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc/vlc.h>
36
37 /* Notification Messages */
38 NSString * VLCMediaPlayerTimeChanged    = @"VLCMediaPlayerTimeChanged";
39 NSString * VLCMediaPlayerStateChanged   = @"VLCMediaPlayerStateChanged";
40
41 NSString * VLCMediaPlayerStateToString(VLCMediaPlayerState state)
42 {
43     static NSString * stateToStrings[] = {
44         [VLCMediaPlayerStateStopped]      = @"VLCMediaPlayerStateStopped",
45         [VLCMediaPlayerStateOpening]      = @"VLCMediaPlayerStateOpening",
46         [VLCMediaPlayerStateBuffering]    = @"VLCMediaPlayerStateBuffering",
47         [VLCMediaPlayerStateEnded]        = @"VLCMediaPlayerStateEnded",
48         [VLCMediaPlayerStateError]        = @"VLCMediaPlayerStateError",
49         [VLCMediaPlayerStatePlaying]      = @"VLCMediaPlayerStatePlaying",
50         [VLCMediaPlayerStatePaused]       = @"VLCMediaPlayerStatePaused"
51     };
52     return stateToStrings[state];
53 }
54
55 /* libvlc event callback */
56 static void HandleMediaInstanceVolumeChanged(const libvlc_event_t * event, void * self)
57 {
58     [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
59                                                    withDelegateMethod:@selector(mediaPlayerVolumeChanged:)
60                                                  withNotificationName:VLCMediaPlayerVolumeChanged];
61 }
62
63 static void HandleMediaTimeChanged(const libvlc_event_t * event, void * self)
64 {
65     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
66     [[VLCEventManager sharedManager] callOnMainThreadObject:self 
67                                                  withMethod:@selector(mediaPlayerTimeChanged:) 
68                                        withArgumentAsObject:[NSNumber numberWithLongLong:event->u.media_player_time_changed.new_time]];
69
70     [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
71                                                    withDelegateMethod:@selector(mediaPlayerTimeChanged:)
72                                                  withNotificationName:VLCMediaPlayerTimeChanged];
73     [pool release];
74 }
75
76 static void HandleMediaPositionChanged(const libvlc_event_t * event, void * self)
77 {
78     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
79
80     [[VLCEventManager sharedManager] callOnMainThreadObject:self 
81                                                  withMethod:@selector(mediaPlayerPositionChanged:) 
82                                        withArgumentAsObject:[NSNumber numberWithFloat:event->u.media_player_position_changed.new_position]];
83     [pool release];
84 }
85
86 static void HandleMediaInstanceStateChanged(const libvlc_event_t * event, void * self)
87 {
88     VLCMediaPlayerState newState;
89
90     if( event->type == libvlc_MediaPlayerPlaying )
91         newState = VLCMediaPlayerStatePlaying;
92     else if( event->type == libvlc_MediaPlayerPaused )
93         newState = VLCMediaPlayerStatePaused;
94     else if( event->type == libvlc_MediaPlayerEndReached )
95         newState = VLCMediaPlayerStateStopped;
96     else if( event->type == libvlc_MediaPlayerEncounteredError )
97         newState = VLCMediaPlayerStateError;
98     else
99     {
100         NSLog(@"%s: Unknown event", __FUNCTION__);
101         return;
102     }
103
104     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
105
106     [[VLCEventManager sharedManager] callOnMainThreadObject:self 
107                                                  withMethod:@selector(mediaPlayerStateChanged:) 
108                                        withArgumentAsObject:[NSNumber numberWithInt:newState]];
109
110     [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
111                                                    withDelegateMethod:@selector(mediaPlayerStateChanged:)
112                                                  withNotificationName:VLCMediaPlayerStateChanged];
113
114     [pool release];
115
116 }
117
118
119 // TODO: Documentation
120 @interface VLCMediaPlayer (Private)
121 - (id)initWithDrawable:(id)aDrawable;
122
123 - (void)registerObservers;
124 - (void)unregisterObservers;
125 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime;
126 - (void)mediaPlayerPositionChanged:(NSNumber *)newTime;
127 - (void)mediaPlayerStateChanged:(NSNumber *)newState;
128 @end
129
130 @implementation VLCMediaPlayer
131
132 /* Bindings */
133 + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
134 {
135     static NSDictionary * dict = nil;
136     NSSet * superKeyPaths;
137     if( !dict )
138     {
139         dict = [[NSDictionary dictionaryWithObjectsAndKeys:
140             [NSSet setWithObject:@"state"], @"playing",
141             [NSSet setWithObjects:@"state", @"media", nil], @"seekable",
142             [NSSet setWithObjects:@"state", @"media", nil], @"canPause",
143             [NSSet setWithObjects:@"state", @"media", nil], @"description",
144             nil] retain];
145     }
146     if( (superKeyPaths = [super keyPathsForValuesAffectingValueForKey: key]) )
147     {
148         NSMutableSet * ret = [NSMutableSet setWithSet:[dict objectForKey: key]];
149         [ret unionSet:superKeyPaths];
150         return ret;
151     }
152     return [dict objectForKey: key];
153 }
154
155 /* Contructor */
156 - (id)init
157 {
158     return [self initWithDrawable:nil];
159 }
160
161 - (id)initWithVideoView:(VLCVideoView *)aVideoView
162 {
163     return [self initWithDrawable: aVideoView];
164 }
165
166 - (id)initWithVideoLayer:(VLCVideoLayer *)aVideoLayer
167 {
168     return [self initWithDrawable: aVideoLayer];
169 }
170
171 - (void)release
172 {
173     @synchronized(self)
174     {
175         if([self retainCount] <= 1)
176         {
177             /* We must make sure we won't receive new event after an upcoming dealloc
178              * We also may receive a -retain in some event callback that may occcur
179              * Before libvlc_event_detach. So this can't happen in dealloc */
180             [self unregisterObservers];
181         }
182         [super release];
183     }
184 }
185
186 - (void)dealloc
187 {
188     // Always get rid of the delegate first so we can stop sending messages to it
189     // TODO: Should we tell the delegate that we're shutting down?
190     delegate = nil;
191
192     libvlc_media_player_release((libvlc_media_player_t *)instance);
193     
194     // Get rid of everything else
195     [media release];
196     [cachedTime release];
197
198     [super dealloc];
199 }
200
201 - (void)setDelegate:(id)value
202 {
203     delegate = value;
204 }
205
206 - (id)delegate
207 {
208     return delegate;
209 }
210
211 - (void)setVideoView:(VLCVideoView *)aVideoView
212 {    
213     [self setDrawable: aVideoView];
214 }
215
216 - (void)setVideoLayer:(VLCVideoLayer *)aVideoLayer
217 {
218     [self setDrawable: aVideoLayer];
219 }
220
221 - (void)setDrawable:(id)aDrawable
222 {
223     // Make sure that this instance has been associated with the drawing canvas.
224     libvlc_exception_t ex;
225     libvlc_exception_init( &ex );
226     libvlc_media_player_set_nsobject(instance, aDrawable, &ex);
227     catch_exception( &ex );
228 }
229
230 - (id)drawable
231 {
232     libvlc_exception_t ex;
233     libvlc_exception_init( &ex );
234     id ret = libvlc_media_player_get_nsobject(instance);
235     catch_exception( &ex );
236     return ret;
237 }
238
239 - (VLCAudio *)audio
240 {
241     return [[VLCLibrary sharedLibrary] audio];
242 }
243
244 - (void)setVideoAspectRatio:(char *)value
245 {
246     libvlc_video_set_aspect_ratio( instance, value, NULL );
247 }
248
249 - (char *)videoAspectRatio
250 {
251     libvlc_exception_t ex;
252     libvlc_exception_init( &ex );
253     char * result = libvlc_video_get_aspect_ratio( instance, &ex );
254     catch_exception( &ex );
255     return result;
256 }
257
258 - (void)setVideoSubTitles:(int)value
259 {
260     libvlc_video_set_spu( instance, value, NULL );
261 }
262
263 - (int)videoSubTitles
264 {
265     libvlc_exception_t ex;
266     libvlc_exception_init( &ex );
267     int result = libvlc_video_get_spu( instance, &ex );
268     catch_exception( &ex );
269     return result;
270 }
271
272 - (void)setVideoCropGeometry:(char *)value
273 {
274     libvlc_video_set_crop_geometry( instance, value, NULL );
275 }
276
277 - (char *)videoCropGeometry
278 {
279     libvlc_exception_t ex;
280     libvlc_exception_init( &ex );
281     char * result = libvlc_video_get_crop_geometry( instance, &ex );
282     catch_exception( &ex );
283     return result;
284 }
285
286 - (void)setVideoTeleText:(int)value
287 {
288     libvlc_video_set_teletext( instance, value, NULL );
289 }
290
291 - (int)videoTeleText
292 {
293     libvlc_exception_t ex;
294     libvlc_exception_init( &ex );
295     int result = libvlc_video_get_teletext( instance, &ex );
296     catch_exception( &ex );
297     return result;
298 }
299
300 - (void)setRate:(float)value
301 {
302     libvlc_media_player_set_rate( instance, value, NULL );
303 }
304
305 - (float)rate
306 {
307     libvlc_exception_t ex;
308     libvlc_exception_init( &ex );
309     float result = libvlc_media_player_get_rate( instance, &ex );
310     catch_exception( &ex );
311     return result;
312 }
313
314 - (NSSize)videoSize
315 {
316     libvlc_exception_t ex;
317     libvlc_exception_init( &ex );
318     NSSize result = NSMakeSize(libvlc_video_get_height((libvlc_media_player_t *)instance, &ex),
319                                libvlc_video_get_width((libvlc_media_player_t *)instance, &ex));
320     catch_exception( &ex );
321     return result;    
322 }
323
324 - (BOOL)hasVideoOut
325 {
326     libvlc_exception_t ex;
327     libvlc_exception_init( &ex );
328     BOOL result = libvlc_media_player_has_vout((libvlc_media_player_t *)instance, &ex);
329     if (libvlc_exception_raised( &ex ))
330     {
331         libvlc_exception_clear( &ex );
332         return NO;
333     }
334     else
335         return result;
336 }
337
338 - (float)framesPerSecond
339 {
340     libvlc_exception_t ex;
341     libvlc_exception_init( &ex );
342     float result = libvlc_media_player_get_fps( (libvlc_media_player_t *)instance, &ex );
343     catch_exception( &ex );
344     return result;
345 }
346
347 - (void)setTime:(VLCTime *)value
348 {
349     libvlc_exception_t ex;
350     libvlc_exception_init( &ex );
351     // Time is managed in seconds, while duration is managed in microseconds
352     // TODO: Redo VLCTime to provide value numberAsMilliseconds, numberAsMicroseconds, numberAsSeconds, numberAsMinutes, numberAsHours
353     libvlc_media_player_set_time( (libvlc_media_player_t *)instance, 
354                                     (value ? [[value numberValue] longLongValue] / 1000 : 0),
355                                     &ex );
356     catch_exception( &ex );
357 }
358
359 - (VLCTime *)time
360 {
361     return cachedTime;
362 }
363
364 - (void)setChapter:(int)value;
365 {
366     libvlc_media_player_set_chapter( instance, value, NULL );
367 }
368
369 - (int)chapter
370 {
371     libvlc_exception_t ex;
372     libvlc_exception_init( &ex );
373     int result = libvlc_media_player_get_chapter( instance, &ex );
374     catch_exception( &ex );
375     return result;
376 }
377
378 - (int)countOfChapters
379 {
380     libvlc_exception_t ex;
381     libvlc_exception_init( &ex );
382     int result = libvlc_media_player_get_chapter_count( instance, &ex );
383     catch_exception( &ex );
384     return result;
385 }
386
387 - (void)setAudioTrack:(int)value
388 {
389     libvlc_audio_set_track( instance, value, NULL );
390 }
391
392 - (int)audioTrack
393 {
394     libvlc_exception_t ex;
395     libvlc_exception_init( &ex );
396     int result = libvlc_audio_get_track( instance, &ex );
397     catch_exception( &ex );
398     return result;
399 }
400
401 - (int)countOfAudioTracks
402 {
403     libvlc_exception_t ex;
404     libvlc_exception_init( &ex );
405     int result = libvlc_audio_get_track_count( instance, &ex );
406     catch_exception( &ex );
407     return result;
408 }
409
410 - (void)setAudioChannel:(int)value
411 {
412     libvlc_audio_set_channel( instance, value, NULL );
413 }
414
415 - (int)audioChannel
416 {
417     libvlc_exception_t ex;
418     libvlc_exception_init( &ex );
419     int result = libvlc_audio_get_channel( instance, &ex );
420     catch_exception( &ex );
421     return result;
422 }
423
424 - (void)setMedia:(VLCMedia *)value
425 {
426     if (media != value)
427     {
428         if (media && [media compare:value] == NSOrderedSame)
429             return;
430         
431         [media release];
432         media = [value retain];
433
434         libvlc_exception_t ex;
435         libvlc_exception_init( &ex );
436         libvlc_media_player_set_media( instance, [media libVLCMediaDescriptor], &ex );
437         catch_exception( &ex );
438     }
439 }
440
441 - (VLCMedia *)media
442 {
443     return media;
444 }
445
446 - (BOOL)play
447 {    
448     libvlc_exception_t ex;
449     libvlc_exception_init( &ex );
450     libvlc_media_player_play( (libvlc_media_player_t *)instance, &ex );
451     catch_exception( &ex );
452     return YES;
453 }
454
455 - (void)pause
456 {
457     if( [NSThread isMainThread] )
458     {
459         /* Hack because we create a dead lock here, when the vout is stopped
460          * and tries to recontact us on the main thread */
461         /* FIXME: to do this properly we need to do some locking. We may want 
462          * to move that to libvlc */
463         [self performSelectorInBackground:@selector(pause) withObject:nil];
464         return;
465     }
466
467     // Return if there is no media available or if the stream is not paused or 
468     // playing something else
469     if (!media || (![self isPlaying] && [self state] != VLCMediaPlayerStatePaused))
470         return;
471
472     // Should never get here.
473     if (!instance)
474         return;
475
476
477     // Pause the stream
478     libvlc_exception_t ex;
479     libvlc_exception_init( &ex );
480     libvlc_media_player_pause( (libvlc_media_player_t *)instance, &ex );
481     catch_exception( &ex );
482     
483     // TODO: Should we record the time in case the media instance is destroyed
484     // then rebuilt?
485 }
486
487 - (void)stop
488 {
489     if( 0 && [NSThread isMainThread] )
490     {
491         /* Hack because we create a dead lock here, when the vout is stopped
492          * and tries to recontact us on the main thread */
493         /* FIXME: to do this properly we need to do some locking. We may want 
494          * to move that to libvlc */
495         [self performSelectorInBackground:@selector(stop) withObject:nil];
496         return;
497     }
498
499     // Return if there is no media available or if the system is not in play status 
500     // or pause status.
501     if (!media)
502         return;
503     
504     libvlc_exception_t ex;
505     libvlc_exception_init( &ex );
506     libvlc_media_player_stop((libvlc_media_player_t *)instance, &ex);
507     catch_exception( &ex );
508 }
509
510 - (void)fastForward
511 {
512     [self fastForwardAtRate: 2.0];
513 }
514
515 - (void)fastForwardAtRate:(float)rate
516 {
517     [self setRate:rate];
518 }
519
520 - (void)rewind
521 {
522     [self rewindAtRate: 2.0];
523 }
524
525 - (void)rewindAtRate:(float)rate
526 {
527     [self setRate: -rate];
528 }
529
530 + (NSSet *)keyPathsForValuesAffectingIsPlaying
531 {
532     return [NSSet setWithObjects:@"state", nil];
533 }
534
535 - (BOOL)isPlaying
536 {
537     VLCMediaPlayerState state = [self state];
538     return ((state == VLCMediaPlayerStateOpening) || (state == VLCMediaPlayerStateBuffering) ||
539             (state == VLCMediaPlayerStatePlaying));
540 }
541
542 - (BOOL)willPlay
543 {
544     libvlc_exception_t ex;
545     libvlc_exception_init( &ex );
546     BOOL ret = libvlc_media_player_will_play( (libvlc_media_player_t *)instance, &ex );
547     if (libvlc_exception_raised(&ex))
548     {
549         libvlc_exception_clear(&ex);
550         return NO;
551     }
552     else
553         return ret;
554 }
555
556 static const VLCMediaPlayerState libvlc_to_local_state[] =
557 {
558     [libvlc_Stopped]    = VLCMediaPlayerStateStopped,
559     [libvlc_Opening]    = VLCMediaPlayerStateOpening,
560     [libvlc_Buffering]  = VLCMediaPlayerStateBuffering,
561     [libvlc_Playing]    = VLCMediaPlayerStatePlaying,
562     [libvlc_Paused]     = VLCMediaPlayerStatePaused,
563     [libvlc_Ended]      = VLCMediaPlayerStateEnded,
564     [libvlc_Error]      = VLCMediaPlayerStateError
565 };
566
567 - (VLCMediaPlayerState)state
568 {
569     return cachedState;
570 }
571
572 - (float)position
573 {
574     return position;
575 }
576
577 - (void)setPosition:(float)newPosition
578 {
579     libvlc_exception_t ex;
580     libvlc_exception_init( &ex );
581     libvlc_media_player_set_position( instance, newPosition, &ex );
582     catch_exception( &ex );
583 }
584
585 - (BOOL)isSeekable
586 {
587     libvlc_exception_t ex;
588     libvlc_exception_init( &ex );
589     BOOL ret = libvlc_media_player_is_seekable( instance, &ex );
590     catch_exception( &ex );
591     return ret;
592 }
593
594 - (BOOL)canPause
595 {
596     libvlc_exception_t ex;
597     libvlc_exception_init( &ex );
598     BOOL ret = libvlc_media_player_can_pause( instance, &ex );
599     catch_exception( &ex );
600     return ret;
601 }
602
603
604 @end
605
606 @implementation VLCMediaPlayer (Private)
607 - (id)initWithDrawable:(id)aDrawable
608 {
609     if (self = [super init])
610     {
611         delegate = nil;
612         media = nil;
613         cachedTime = [[VLCTime nullTime] retain];
614         position = 0.0f;
615         cachedState = VLCMediaPlayerStateStopped;
616
617         // Create a media instance, it doesn't matter what library we start off with
618         // it will change depending on the media descriptor provided to the media
619         // instance
620         libvlc_exception_t ex;
621         libvlc_exception_init( &ex );
622         instance = (void *)libvlc_media_player_new([VLCLibrary sharedInstance], &ex);
623         catch_exception( &ex );
624         
625         [self registerObservers];
626         
627         [self setDrawable:aDrawable];
628     }
629     return self;
630 }
631
632 - (void)registerObservers
633 {
634     libvlc_exception_t ex;
635     libvlc_exception_init( &ex );
636
637     // Attach event observers into the media instance
638     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, &ex );
639     libvlc_event_attach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, &ex );
640     libvlc_event_attach( p_em, libvlc_MediaPlayerPaused,          HandleMediaInstanceStateChanged, self, &ex );
641     libvlc_event_attach( p_em, libvlc_MediaPlayerEndReached,      HandleMediaInstanceStateChanged, self, &ex );
642     /* FIXME: We may want to turn that off when none is interested by that */
643     libvlc_event_attach( p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged,      self, &ex );
644     libvlc_event_attach( p_em, libvlc_MediaPlayerTimeChanged,     HandleMediaTimeChanged,          self, &ex );
645     catch_exception( &ex );
646 }
647
648 - (void)unregisterObservers
649 {
650     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, NULL );
651     libvlc_event_detach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, NULL );
652     libvlc_event_detach( p_em, libvlc_MediaPlayerPaused,          HandleMediaInstanceStateChanged, self, NULL );
653     libvlc_event_detach( p_em, libvlc_MediaPlayerEndReached,      HandleMediaInstanceStateChanged, self, NULL );
654     libvlc_event_detach( p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged,      self, NULL );
655     libvlc_event_detach( p_em, libvlc_MediaPlayerTimeChanged,     HandleMediaTimeChanged,          self, NULL );
656 }
657
658 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime
659 {
660     [self willChangeValueForKey:@"time"];
661     [cachedTime release];
662     cachedTime = [[VLCTime timeWithNumber:newTime] retain];
663
664     [self didChangeValueForKey:@"time"];
665 }
666
667 - (void)mediaPlayerPositionChanged:(NSNumber *)newPosition
668 {
669     [self willChangeValueForKey:@"position"];
670     position = [newPosition floatValue];
671     [self didChangeValueForKey:@"position"];
672 }
673
674 - (void)mediaPlayerStateChanged:(NSNumber *)newState
675 {
676     [self willChangeValueForKey:@"state"];
677     cachedState = [newState intValue];
678     [self didChangeValueForKey:@"state"];
679 }
680 @end