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
9 * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
10 * Faustion Osuna <enrique.osuna # gmail.com>
11 * Felix Paul Kühne <fkuehne # videolan.org>
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.
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.
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 *****************************************************************************/
28 #import "VLCLibrary.h"
29 #import "VLCMediaPlayer.h"
30 #import "VLCEventManager.h"
31 #import "VLCLibVLCBridging.h"
32 #import "VLCVideoView.h"
37 /* prevent system sleep */
38 #import <CoreServices/CoreServices.h>
39 /* FIXME: Ugly hack! */
41 #import <CoreServices/../Frameworks/OSServices.framework/Headers/Power.h>
46 /* Notification Messages */
47 NSString * VLCMediaPlayerTimeChanged = @"VLCMediaPlayerTimeChanged";
48 NSString * VLCMediaPlayerStateChanged = @"VLCMediaPlayerStateChanged";
50 NSString * VLCMediaPlayerStateToString(VLCMediaPlayerState state)
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"
61 return stateToStrings[state];
64 /* libvlc event callback */
65 static void HandleMediaInstanceVolumeChanged(const libvlc_event_t * event, void * self)
67 [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
68 withDelegateMethod:@selector(mediaPlayerVolumeChanged:)
69 withNotificationName:VLCMediaPlayerVolumeChanged];
72 static void HandleMediaTimeChanged(const libvlc_event_t * event, void * self)
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]];
79 [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
80 withDelegateMethod:@selector(mediaPlayerTimeChanged:)
81 withNotificationName:VLCMediaPlayerTimeChanged];
85 static void HandleMediaPositionChanged(const libvlc_event_t * event, void * self)
87 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
89 [[VLCEventManager sharedManager] callOnMainThreadObject:self
90 withMethod:@selector(mediaPlayerPositionChanged:)
91 withArgumentAsObject:[NSNumber numberWithFloat:event->u.media_player_position_changed.new_position]];
95 static void HandleMediaInstanceStateChanged(const libvlc_event_t * event, void * self)
97 VLCMediaPlayerState newState;
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;
109 NSLog(@"%s: Unknown event", __FUNCTION__);
113 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
115 [[VLCEventManager sharedManager] callOnMainThreadObject:self
116 withMethod:@selector(mediaPlayerStateChanged:)
117 withArgumentAsObject:[NSNumber numberWithInt:newState]];
119 [[VLCEventManager sharedManager] callOnMainThreadDelegateOfObject:self
120 withDelegateMethod:@selector(mediaPlayerStateChanged:)
121 withNotificationName:VLCMediaPlayerStateChanged];
127 static void HandleMediaPlayerMediaChanged(const libvlc_event_t * event, void * self)
129 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
131 [[VLCEventManager sharedManager] callOnMainThreadObject:self
132 withMethod:@selector(mediaPlayerMediaChanged:)
133 withArgumentAsObject:[VLCMedia mediaWithLibVLCMediaDescriptor:event->u.media_player_media_changed.new_media]];
140 // TODO: Documentation
141 @interface VLCMediaPlayer (Private)
142 - (id)initWithDrawable:(id)aDrawable;
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;
152 @implementation VLCMediaPlayer
155 + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
157 static NSDictionary * dict = nil;
158 NSSet * superKeyPaths;
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",
168 if( (superKeyPaths = [super keyPathsForValuesAffectingValueForKey: key]) )
170 NSMutableSet * ret = [NSMutableSet setWithSet:[dict objectForKey: key]];
171 [ret unionSet:superKeyPaths];
174 return [dict objectForKey: key];
180 return [self initWithDrawable:nil];
183 - (id)initWithVideoView:(VLCVideoView *)aVideoView
185 return [self initWithDrawable: aVideoView];
188 - (id)initWithVideoLayer:(VLCVideoLayer *)aVideoLayer
190 return [self initWithDrawable: aVideoLayer];
197 if([self retainCount] <= 1)
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];
210 NSAssert(libvlc_media_player_get_state(instance) == libvlc_Stopped, @"You released the media player before ensuring that it is stopped");
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?
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);
221 libvlc_media_player_release(instance);
223 // Get rid of everything else
225 [cachedTime release];
226 [cachedRemainingTime release];
232 - (void)setDelegate:(id)value
242 - (void)setVideoView:(VLCVideoView *)aVideoView
244 [self setDrawable: aVideoView];
247 - (void)setVideoLayer:(VLCVideoLayer *)aVideoLayer
249 [self setDrawable: aVideoLayer];
252 - (void)setDrawable:(id)aDrawable
254 // Make sure that this instance has been associated with the drawing canvas.
255 libvlc_media_player_set_nsobject(instance, aDrawable);
260 return libvlc_media_player_get_nsobject(instance);
265 return [[VLCLibrary sharedLibrary] audio];
269 #pragma mark Subtitles
271 - (void)setCurrentVideoSubTitleIndex:(NSUInteger)index
273 libvlc_video_set_spu(instance, (int)index);
276 - (NSUInteger)currentVideoSubTitleIndex
278 NSInteger count = libvlc_video_get_spu_count(instance);
283 return libvlc_video_get_spu(instance);
286 - (BOOL)openVideoSubTitlesFromFile:(NSString *)path
288 return libvlc_video_set_subtitle_file(instance, [path UTF8String]);
291 - (NSArray *)videoSubTitles
293 libvlc_track_description_t *currentTrack = libvlc_video_get_spu_description(instance);
295 NSMutableArray *tempArray = [NSMutableArray array];
296 while (currentTrack) {
297 [tempArray addObject:[NSString stringWithUTF8String:currentTrack->psz_name]];
298 currentTrack = currentTrack->p_next;
300 libvlc_track_description_release(currentTrack);
301 return [NSArray arrayWithArray: tempArray];
306 #pragma mark Video Crop geometry
308 - (void)setVideoCropGeometry:(char *)value
310 libvlc_video_set_crop_geometry(instance, value);
313 - (char *)videoCropGeometry
315 char * result = libvlc_video_get_crop_geometry(instance);
319 - (void)setVideoAspectRatio:(char *)value
321 libvlc_video_set_aspect_ratio( instance, value );
324 - (char *)videoAspectRatio
326 char * result = libvlc_video_get_aspect_ratio( instance );
330 - (void)saveVideoSnapshotAt:(NSString *)path withWidth:(NSUInteger)width andHeight:(NSUInteger)height
332 int failure = libvlc_video_take_snapshot(instance, 0, [path UTF8String], width, height);
334 [[NSException exceptionWithName:@"Can't take a video snapshot" reason:@"No video output" userInfo:nil] raise];
337 - (void)setDeinterlaceFilter:(NSString *)name
339 libvlc_video_set_deinterlace(instance, [name UTF8String]);
342 - (void)setRate:(float)value
344 libvlc_media_player_set_rate(instance, value);
349 return libvlc_media_player_get_rate(instance);
354 unsigned height = 0, width = 0;
355 int failure = libvlc_video_get_size(instance, 0, &width, &height);
357 [[NSException exceptionWithName:@"Can't get video size" reason:@"No video output" userInfo:nil] raise];
358 return NSMakeSize(width, height);
363 return libvlc_media_player_has_vout(instance);
366 - (float)framesPerSecond
368 return libvlc_media_player_get_fps(instance);
371 - (void)setTime:(VLCTime *)value
373 // Time is managed in seconds, while duration is managed in microseconds
374 // TODO: Redo VLCTime to provide value numberAsMilliseconds, numberAsMicroseconds, numberAsSeconds, numberAsMinutes, numberAsHours
375 libvlc_media_player_set_time(instance, value ? [[value numberValue] longLongValue] : 0);
383 - (VLCTime *)remainingTime
385 return cachedRemainingTime;
390 return libvlc_media_player_get_fps(instance);
394 #pragma mark Chapters
395 - (void)setCurrentChapterIndex:(NSUInteger)value;
397 libvlc_media_player_set_chapter(instance, value);
400 - (NSUInteger)currentChapterIndex
402 NSInteger count = libvlc_media_player_get_chapter_count(instance);
405 NSUInteger result = libvlc_media_player_get_chapter(instance);
411 libvlc_media_player_next_chapter(instance);
414 - (void)previousChapter
416 libvlc_media_player_previous_chapter(instance);
419 - (NSArray *)chaptersForTitleIndex:(NSUInteger)title
421 NSInteger count = libvlc_media_player_get_chapter_count(instance);
423 return [NSArray array];
425 libvlc_track_description_t *tracks = libvlc_video_get_chapter_description(instance, title);
426 NSMutableArray *tempArray = [NSMutableArray array];
428 for (i = 0; i < count ; i++)
430 [tempArray addObject:[NSString stringWithUTF8String:tracks->psz_name]];
431 tracks = tracks->p_next;
433 libvlc_track_description_release(tracks);
434 return [NSArray arrayWithArray:tempArray];
440 - (void)setCurrentTitleIndex:(NSUInteger)value
442 libvlc_media_player_set_title(instance, value);
445 - (NSUInteger)currentTitleIndex
447 NSInteger count = libvlc_media_player_get_title_count(instance);
451 return libvlc_media_player_get_title(instance);
454 - (NSUInteger)countOfTitles
456 NSUInteger result = libvlc_media_player_get_title_count(instance);
462 libvlc_track_description_t *tracks = libvlc_video_get_title_description(instance);
463 NSMutableArray *tempArray = [NSMutableArray array];
465 for (i = 0; i < [self countOfTitles] ; i++)
467 [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
468 tracks = tracks->p_next;
470 libvlc_track_description_release(tracks);
471 return [NSArray arrayWithArray: tempArray];
475 #pragma mark Audio tracks
476 - (void)setCurrentAudioTrackIndex:(NSUInteger)value
478 libvlc_audio_set_track( instance, (int)value);
481 - (NSUInteger)currentAudioTrackIndex
483 NSInteger count = libvlc_audio_get_track_count(instance);
487 NSUInteger result = libvlc_audio_get_track(instance);
491 - (NSArray *)audioTracks
493 NSInteger count = libvlc_audio_get_track_count(instance);
495 return [NSArray array];
497 libvlc_track_description_t *tracks = libvlc_audio_get_track_description(instance);
498 NSMutableArray *tempArray = [NSMutableArray array];
500 for (i = 0; i < count ; i++)
502 [tempArray addObject:[NSString stringWithUTF8String: tracks->psz_name]];
503 tracks = tracks->p_next;
505 libvlc_track_description_release(tracks);
507 return [NSArray arrayWithArray: tempArray];
510 - (void)setAudioChannel:(NSInteger)value
512 libvlc_audio_set_channel(instance, value);
515 - (NSInteger)audioChannel
517 return libvlc_audio_get_channel(instance);
520 - (void)setMedia:(VLCMedia *)value
524 if (media && [media compare:value] == NSOrderedSame)
528 media = [value retain];
530 libvlc_media_player_set_media(instance, [media libVLCMediaDescriptor]);
541 libvlc_media_player_play(instance);
547 if( [NSThread isMainThread] )
549 /* Hack because we create a dead lock here, when the vout is stopped
550 * and tries to recontact us on the main thread */
551 /* FIXME: to do this properly we need to do some locking. We may want
552 * to move that to libvlc */
553 [self performSelectorInBackground:@selector(pause) withObject:nil];
558 libvlc_media_player_pause(instance);
563 libvlc_media_player_stop(instance);
566 - (void)gotoNextFrame
568 libvlc_media_player_next_frame(instance);
574 [self fastForwardAtRate: 2.0];
577 - (void)fastForwardAtRate:(float)rate
584 [self rewindAtRate: 2.0];
587 - (void)rewindAtRate:(float)rate
589 [self setRate: -rate];
592 - (void)jumpBackward:(NSInteger)interval
594 if( [self isSeekable] )
596 interval = interval * 1000;
597 [self setTime: [VLCTime timeWithInt: ([[self time] intValue] - interval)]];
601 - (void)jumpForward:(NSInteger)interval
603 if( [self isSeekable] )
605 interval = interval * 1000;
606 [self setTime: [VLCTime timeWithInt: ([[self time] intValue] + interval)]];
610 - (void)extraShortJumpBackward
612 [self jumpBackward:3];
615 - (void)extraShortJumpForward
617 [self jumpForward:3];
620 - (void)shortJumpBackward
622 [self jumpBackward:10];
625 - (void)shortJumpForward
627 [self jumpForward:10];
630 - (void)mediumJumpBackward
632 [self jumpBackward:60];
635 - (void)mediumJumpForward
637 [self jumpForward:60];
640 - (void)longJumpBackward
642 [self jumpBackward:300];
645 - (void)longJumpForward
647 [self jumpForward:300];
650 + (NSSet *)keyPathsForValuesAffectingIsPlaying
652 return [NSSet setWithObjects:@"state", nil];
657 VLCMediaPlayerState state = [self state];
658 return ((state == VLCMediaPlayerStateOpening) || (state == VLCMediaPlayerStateBuffering) ||
659 (state == VLCMediaPlayerStatePlaying));
664 return libvlc_media_player_will_play(instance);
667 static const VLCMediaPlayerState libvlc_to_local_state[] =
669 [libvlc_Stopped] = VLCMediaPlayerStateStopped,
670 [libvlc_Opening] = VLCMediaPlayerStateOpening,
671 [libvlc_Buffering] = VLCMediaPlayerStateBuffering,
672 [libvlc_Playing] = VLCMediaPlayerStatePlaying,
673 [libvlc_Paused] = VLCMediaPlayerStatePaused,
674 [libvlc_Ended] = VLCMediaPlayerStateEnded,
675 [libvlc_Error] = VLCMediaPlayerStateError
678 - (VLCMediaPlayerState)state
688 - (void)setPosition:(float)newPosition
690 libvlc_media_player_set_position(instance, newPosition);
695 return libvlc_media_player_is_seekable(instance);
700 return libvlc_media_player_can_pause(instance);
703 - (void *)libVLCMediaPlayer
709 @implementation VLCMediaPlayer (Private)
710 - (id)initWithDrawable:(id)aDrawable
712 if (self = [super init])
716 cachedTime = [[VLCTime nullTime] retain];
717 cachedRemainingTime = [[VLCTime nullTime] retain];
719 cachedState = VLCMediaPlayerStateStopped;
721 // Create a media instance, it doesn't matter what library we start off with
722 // it will change depending on the media descriptor provided to the media
724 libvlc_exception_t ex;
725 libvlc_exception_init( &ex );
726 instance = libvlc_media_player_new([VLCLibrary sharedInstance]);
727 catch_exception( &ex );
729 [self registerObservers];
731 [self setDrawable:aDrawable];
736 - (void)registerObservers
738 // Attach event observers into the media instance
739 libvlc_event_manager_t * p_em = libvlc_media_player_event_manager(instance);
740 libvlc_event_attach(p_em, libvlc_MediaPlayerPlaying, HandleMediaInstanceStateChanged, self);
741 libvlc_event_attach(p_em, libvlc_MediaPlayerPaused, HandleMediaInstanceStateChanged, self);
742 libvlc_event_attach(p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self);
743 libvlc_event_attach(p_em, libvlc_MediaPlayerEndReached, HandleMediaInstanceStateChanged, self);
744 /* FIXME: We may want to turn that off when none is interested by that */
745 libvlc_event_attach(p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged, self);
746 libvlc_event_attach(p_em, libvlc_MediaPlayerTimeChanged, HandleMediaTimeChanged, self);
747 libvlc_event_attach(p_em, libvlc_MediaPlayerMediaChanged, HandleMediaPlayerMediaChanged, self);
750 - (void)unregisterObservers
752 libvlc_event_manager_t * p_em = libvlc_media_player_event_manager(instance);
753 libvlc_event_detach(p_em, libvlc_MediaPlayerPlaying, HandleMediaInstanceStateChanged, self);
754 libvlc_event_detach(p_em, libvlc_MediaPlayerPaused, HandleMediaInstanceStateChanged, self);
755 libvlc_event_detach(p_em, libvlc_MediaPlayerEncounteredError, HandleMediaInstanceStateChanged, self);
756 libvlc_event_detach(p_em, libvlc_MediaPlayerEndReached, HandleMediaInstanceStateChanged, self);
757 libvlc_event_detach(p_em, libvlc_MediaPlayerPositionChanged, HandleMediaPositionChanged, self);
758 libvlc_event_detach(p_em, libvlc_MediaPlayerTimeChanged, HandleMediaTimeChanged, self);
759 libvlc_event_detach(p_em, libvlc_MediaPlayerMediaChanged, HandleMediaPlayerMediaChanged, self);
762 - (void)mediaPlayerTimeChanged:(NSNumber *)newTime
764 [self willChangeValueForKey:@"time"];
765 [self willChangeValueForKey:@"remainingTime"];
766 [cachedTime release];
767 cachedTime = [[VLCTime timeWithNumber:newTime] retain];
768 [cachedRemainingTime release];
769 double currentTime = [[cachedTime numberValue] doubleValue];
770 double remaining = currentTime / position * (1 - position);
771 cachedRemainingTime = [[VLCTime timeWithNumber:[NSNumber numberWithDouble:-remaining]] retain];
772 [self didChangeValueForKey:@"remainingTime"];
773 [self didChangeValueForKey:@"time"];
778 UpdateSystemActivity(UsrActivity);
781 - (void)mediaPlayerPositionChanged:(NSNumber *)newPosition
783 // This seems to be the most relevant place to delay sleeping and screen saver.
786 [self willChangeValueForKey:@"position"];
787 position = [newPosition floatValue];
788 [self didChangeValueForKey:@"position"];
791 - (void)mediaPlayerStateChanged:(NSNumber *)newState
793 [self willChangeValueForKey:@"state"];
794 cachedState = [newState intValue];
795 [self didChangeValueForKey:@"state"];
798 - (void)mediaPlayerMediaChanged:(VLCMedia *)newMedia
800 [self willChangeValueForKey:@"media"];
801 if (media != newMedia)
804 media = [newMedia retain];
806 [self didChangeValueForKey:@"media"];