]> git.sesse.net Git - vlc/blob - projects/macosx/framework/Sources/VLCMediaPlayer.m
493b471605650f6ecc5b0ec178fce82fff77dd56
[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     // Pause the stream
468     libvlc_exception_t ex;
469     libvlc_exception_init( &ex );
470     libvlc_media_player_pause( (libvlc_media_player_t *)instance, &ex );
471     catch_exception( &ex );
472 }
473
474 - (void)stop
475 {
476     if( 0 && [NSThread isMainThread] )
477     {
478         /* Hack because we create a dead lock here, when the vout is stopped
479          * and tries to recontact us on the main thread */
480         /* FIXME: to do this properly we need to do some locking. We may want 
481          * to move that to libvlc */
482         [self performSelectorInBackground:@selector(stop) withObject:nil];
483         return;
484     }
485     
486     libvlc_exception_t ex;
487     libvlc_exception_init( &ex );
488     libvlc_media_player_stop((libvlc_media_player_t *)instance, &ex);
489     catch_exception( &ex );
490 }
491
492 - (void)fastForward
493 {
494     [self fastForwardAtRate: 2.0];
495 }
496
497 - (void)fastForwardAtRate:(float)rate
498 {
499     [self setRate:rate];
500 }
501
502 - (void)rewind
503 {
504     [self rewindAtRate: 2.0];
505 }
506
507 - (void)rewindAtRate:(float)rate
508 {
509     [self setRate: -rate];
510 }
511
512 + (NSSet *)keyPathsForValuesAffectingIsPlaying
513 {
514     return [NSSet setWithObjects:@"state", nil];
515 }
516
517 - (BOOL)isPlaying
518 {
519     VLCMediaPlayerState state = [self state];
520     return ((state == VLCMediaPlayerStateOpening) || (state == VLCMediaPlayerStateBuffering) ||
521             (state == VLCMediaPlayerStatePlaying));
522 }
523
524 - (BOOL)willPlay
525 {
526     libvlc_exception_t ex;
527     libvlc_exception_init( &ex );
528     BOOL ret = libvlc_media_player_will_play( (libvlc_media_player_t *)instance, &ex );
529     if (libvlc_exception_raised(&ex))
530     {
531         libvlc_exception_clear(&ex);
532         return NO;
533     }
534     else
535         return ret;
536 }
537
538 static const VLCMediaPlayerState libvlc_to_local_state[] =
539 {
540     [libvlc_Stopped]    = VLCMediaPlayerStateStopped,
541     [libvlc_Opening]    = VLCMediaPlayerStateOpening,
542     [libvlc_Buffering]  = VLCMediaPlayerStateBuffering,
543     [libvlc_Playing]    = VLCMediaPlayerStatePlaying,
544     [libvlc_Paused]     = VLCMediaPlayerStatePaused,
545     [libvlc_Ended]      = VLCMediaPlayerStateEnded,
546     [libvlc_Error]      = VLCMediaPlayerStateError
547 };
548
549 - (VLCMediaPlayerState)state
550 {
551     return cachedState;
552 }
553
554 - (float)position
555 {
556     return position;
557 }
558
559 - (void)setPosition:(float)newPosition
560 {
561     libvlc_exception_t ex;
562     libvlc_exception_init( &ex );
563     libvlc_media_player_set_position( instance, newPosition, &ex );
564     catch_exception( &ex );
565 }
566
567 - (BOOL)isSeekable
568 {
569     libvlc_exception_t ex;
570     libvlc_exception_init( &ex );
571     BOOL ret = libvlc_media_player_is_seekable( instance, &ex );
572     catch_exception( &ex );
573     return ret;
574 }
575
576 - (BOOL)canPause
577 {
578     libvlc_exception_t ex;
579     libvlc_exception_init( &ex );
580     BOOL ret = libvlc_media_player_can_pause( instance, &ex );
581     catch_exception( &ex );
582     return ret;
583 }
584
585 - (void *)libVLCMediaPlayer
586 {
587     return instance;
588 }
589 @end
590
591 @implementation VLCMediaPlayer (Private)
592 - (id)initWithDrawable:(id)aDrawable
593 {
594     if (self = [super init])
595     {
596         delegate = nil;
597         media = nil;
598         cachedTime = [[VLCTime nullTime] retain];
599         position = 0.0f;
600         cachedState = VLCMediaPlayerStateStopped;
601
602         // Create a media instance, it doesn't matter what library we start off with
603         // it will change depending on the media descriptor provided to the media
604         // instance
605         libvlc_exception_t ex;
606         libvlc_exception_init( &ex );
607         instance = (void *)libvlc_media_player_new([VLCLibrary sharedInstance], &ex);
608         catch_exception( &ex );
609         
610         [self registerObservers];
611         
612         [self setDrawable:aDrawable];
613     }
614     return self;
615 }
616
617 - (void)registerObservers
618 {
619     libvlc_exception_t ex;
620     libvlc_exception_init( &ex );
621
622     // Attach event observers into the media instance
623     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, &ex );
624     libvlc_event_attach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, &ex );
625     libvlc_event_attach( p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self, &ex );
626     libvlc_event_attach( p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self, &ex );
627     libvlc_event_attach( p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self, &ex );
628     /* FIXME: We may want to turn that off when none is interested by that */
629     libvlc_event_attach( p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged,      self, &ex );
630     libvlc_event_attach( p_em, libvlc_MediaPlayerTimeChanged,     HandleMediaTimeChanged,          self, &ex );
631     catch_exception( &ex );
632 }
633
634 - (void)unregisterObservers
635 {
636     libvlc_event_manager_t * p_em = libvlc_media_player_event_manager( instance, NULL );
637     libvlc_event_detach( p_em, libvlc_MediaPlayerPlaying,          HandleMediaInstanceStateChanged, self, NULL );
638     libvlc_event_detach( p_em, libvlc_MediaPlayerPaused,           HandleMediaInstanceStateChanged, self, NULL );
639     libvlc_event_detach( p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self, NULL );
640     libvlc_event_detach( p_em, libvlc_MediaPlayerEndReached,       HandleMediaInstanceStateChanged, self, NULL );
641     libvlc_event_detach( p_em, libvlc_MediaPlayerPositionChanged,  HandleMediaPositionChanged,      self, NULL );
642     libvlc_event_detach( p_em, libvlc_MediaPlayerTimeChanged,      HandleMediaTimeChanged,          self, NULL );
643 }
644
645 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime
646 {
647     [self willChangeValueForKey:@"time"];
648     [cachedTime release];
649     cachedTime = [[VLCTime timeWithNumber:newTime] retain];
650
651     [self didChangeValueForKey:@"time"];
652 }
653
654 - (void)mediaPlayerPositionChanged:(NSNumber *)newPosition
655 {
656     [self willChangeValueForKey:@"position"];
657     position = [newPosition floatValue];
658     [self didChangeValueForKey:@"position"];
659 }
660
661 - (void)mediaPlayerStateChanged:(NSNumber *)newState
662 {
663     [self willChangeValueForKey:@"state"];
664     cachedState = [newState intValue];
665     [self didChangeValueForKey:@"state"];
666 }
667 @end