VLCMedia.m 17.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*****************************************************************************
 * VLCMedia.m: VLC.framework VLCMedia implementation
 *****************************************************************************
 * Copyright (C) 2007 Pierre d'Herbemont
 * Copyright (C) 2007 the VideoLAN team
 * $Id$
 *
 * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

25 26
#import "VLCMedia.h"
#import "VLCMediaList.h"
27 28
#import "VLCEventManager.h"
#import "VLCLibrary.h"
29
#import "VLCLibVLCBridging.h"
30 31
#include <vlc/libvlc.h>

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
/* Meta Dictionary Keys */
NSString *VLCMetaInformationTitle       = @"title";
NSString *VLCMetaInformationArtist      = @"artist";
NSString *VLCMetaInformationGenre       = @"genre";
NSString *VLCMetaInformationCopyright   = @"copyright";
NSString *VLCMetaInformationAlbum       = @"album";
NSString *VLCMetaInformationTrackNumber = @"trackNumber";
NSString *VLCMetaInformationDescription = @"description";
NSString *VLCMetaInformationRating      = @"rating";
NSString *VLCMetaInformationDate        = @"date";
NSString *VLCMetaInformationSetting     = @"setting";
NSString *VLCMetaInformationURL         = @"url";
NSString *VLCMetaInformationLanguage    = @"language";
NSString *VLCMetaInformationNowPlaying  = @"nowPlaying";
NSString *VLCMetaInformationPublisher   = @"publisher";
NSString *VLCMetaInformationEncodedBy   = @"encodedBy";
NSString *VLCMetaInformationArtworkURL  = @"artworkURL";
NSString *VLCMetaInformationArtwork     = @"artwork";
NSString *VLCMetaInformationTrackID     = @"trackID";
51

52 53 54 55
/* Notification Messages */
NSString *VLCMediaMetaChanged           = @"VLCMediaMetaChanged";
//NSString *VLCMediaSubItemAdded        = @"VLCMediaSubItemAdded";
//NSString *VLCMediaSubItemDeleted      = @"VLCMediaSubItemDeleted";
56 57

/* libvlc event callback */
58 59 60 61 62 63 64 65 66 67 68 69 70
//static void HandleMediaSubItemAdded(const libvlc_event_t *event, void *self)
//{
//  [[VLCEventManager sharedManager] callOnMainThreadObject:self
//                                               withMethod:@selector(subItemAdded:)
//                                     withArgumentAsObject:(id)event->u.media_descriptor_subitem_added.new_child];
//}
//
//static void HandleMediaSubItemDeleted(const libvlc_event_t *event, void *self)
//{
//  [[VLCEventManager sharedManager] callOnMainThreadObject:self
//                                               withMethod:@selector(subItemDeleted)
//                                     withArgumentAsObject:nil];
//}
71

72
static void HandleMediaMetaChanged(const libvlc_event_t *event, void *self)
73
{
74 75 76 77 78 79
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    [[VLCEventManager sharedManager] callOnMainThreadObject:self
                                                 withMethod:@selector(metaChanged:)
                                       withArgumentAsObject:[NSNumber numberWithInt:(int)event->u.media_descriptor_meta_changed.meta_type]];
    [pool release];
80 81
}

82
static void HandleMediaDurationChanged(const libvlc_event_t *event, void *self)
83
{
84 85 86 87 88 89 90
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    //[[VLCEventManager sharedManager] callOnMainThreadObject:self
//                                                 withMethod:@selector(setLength:)
//                                       withArgumentAsObject:[VLCTime timeWithNumber:
//                                           [NSNumber numberWithLongLong:event->u.media_descriptor_duration_changed.new_duration]]];
    [pool release];
91 92 93
}


94
// TODO: Documentation
95
@interface VLCMedia (Private)
96 97 98
/* Statics */
+ (libvlc_meta_t)stringToMetaType:(NSString *)string;
+ (NSString *)metaTypeToString:(libvlc_meta_t)type;
99

100 101
/* Initializers */
- (void)initInternalMediaDescriptor;
102

103 104 105 106 107
/* Operations */
- (BOOL)setMetaValue:(char *)value forKey:(NSString *)key;
- (void)fetchMetaInformation;
- (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL;
- (void)notifyChangeForKey:(NSString *)key withOldValue:(id)oldValue;
108

109 110 111 112 113
/* Callback Methods */
//- (void)subItemAdded:(libvlc_media_descriptor_t *)child;
//- (void)subItemRemoved:(libvlc_media_descriptor_t *)child;
- (void)metaChanged:(NSNumber *)metaType;
@end
114

115 116 117 118 119 120 121 122 123
@implementation VLCMedia
+ (id)mediaWithURL:(NSString *)aURL;
{
    // For some unknown reason, compiler kept shooting me a warning saying:
    //  warning: passing argument 1 of 'initWithURL:' from distinct Objective-C type
    // Research on the net shows that the error means that the argument passed
    // is not compatible with the expected argument.  Doesn't make sense, however
    // the warning goes away when it is casted it with "id".
    return [[[VLCMedia alloc] initWithURL:(id)aURL] autorelease];
124 125
}

126
- (id)initWithURL:(NSString *)aURL
127
{        
128 129
    if (self = [super init])
    {
130
        
131
        libvlc_exception_t ex;
132
        libvlc_exception_init(&ex);
133
        
134
        p_md = libvlc_media_descriptor_new([VLCLibrary sharedInstance],
135
                                           [aURL cString],
136 137 138
                                           &ex);
        quit_on_exception(&ex);
        
139
        url = [aURL copy];
140 141 142 143 144 145 146 147
        delegate = nil;
        metaDictionary = nil;
        
        // This value is set whenever the demuxer figures out what the length is.
        // TODO: Easy way to tell the length of the movie without having to instiate the demuxer.  Maybe cached info?
        length = nil;

        [self initInternalMediaDescriptor];
148 149 150 151 152 153 154 155 156 157 158 159 160
    }
    return self;
}

- (void)release
{
    @synchronized(self)
    {
        if([self retainCount] <= 1)
        {
            /* We must make sure we won't receive new event after an upcoming dealloc
             * We also may receive a -retain in some event callback that may occcur
             * Before libvlc_event_detach. So this can't happen in dealloc */
161 162 163
            libvlc_event_manager_t *p_em = libvlc_media_descriptor_event_manager(p_md, NULL);
//            libvlc_event_detach(p_em, libvlc_MediaDescriptorSubItemAdded,    HandleMediaSubItemAdded,    self, NULL);
//            libvlc_event_detach(p_em, libvlc_MediaDescriptorSubItemDeleted,  HandleMediaSubItemAdded,    self, NULL);
164 165
            libvlc_event_detach(p_em, libvlc_MediaDescriptorMetaChanged,     HandleMediaMetaChanged,     self, NULL);
            libvlc_event_detach(p_em, libvlc_MediaDescriptorDurationChanged, HandleMediaDurationChanged, self, NULL);
166 167 168 169 170
        }
        [super release];
    }
}

171
- (void)dealloc
172
{
173 174 175 176 177
    // Testing to see if the pointer exists is not required, if the pointer is null
    // then the release message is not sent to it.
    [self setDelegate:nil];
    [self setLength:nil];

178
    [url release];
179 180
    [subitems release];
    [metaDictionary release];
181

182
    libvlc_media_descriptor_release( p_md );
183

184 185 186
    [super dealloc];
}

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
- (NSString *)description
{
    NSString *result = nil;
    if (metaDictionary)
        result = [metaDictionary objectForKey:VLCMetaInformationTitle];
    return (result ? result : url);
}

- (NSComparisonResult)compare:(VLCMedia *)media
{
    if (self == media)
        return NSOrderedSame;
    else if (!media)
        return NSOrderedDescending;
    else
        return [[self url] compare:[media url]];
}

205 206 207 208 209
- (NSString *)url
{
    return [[url copy] autorelease];
}

210
- (VLCMediaList *)subitems
211 212 213 214
{
    return subitems;
}

215
- (VLCTime *)length
216
{
217 218 219
    if (!length) 
    {
        // Try figuring out what the length is
220
        long long duration = libvlc_media_descriptor_get_duration( p_md, NULL );
221 222 223 224 225 226 227 228 229
        if (duration > -1) 
        {
            [self setLength:[VLCTime timeWithNumber:[NSNumber numberWithLongLong:duration]]];
            return [[length retain] autorelease];
        } 
    }
    return [VLCTime nullTime];
}

230 231
- (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
{
232 233 234 235 236 237 238 239 240
#define CLOCK_FREQ      1000000
#define THREAD_SLEEP    ((long long)(0.010*CLOCK_FREQ))

    if (![url hasPrefix:@"file://"])
        return [self length];
    else if (!length)
    {
        while (!length && ![self isPreparsed] && [aDate timeIntervalSinceNow] > 0)
        {
241
            usleep( THREAD_SLEEP );
242 243 244 245 246 247 248 249
        }
        
        // So we're done waiting, but sometimes we trap the fact that the parsing
        // was done before the length gets assigned, so lets go ahead and assign
        // it ourselves.
        if (!length)
            return [self length];
    }
250 251
#undef CLOCK_FREQ
#undef THREAD_SLEEP
252
    return [[length retain] autorelease];
253
}
254 255 256

- (BOOL)isPreparsed
{
257
    return libvlc_media_descriptor_is_preparsed( p_md, NULL );
258 259 260 261 262 263 264 265 266 267 268 269
}

- (NSDictionary *)metaDictionary
{
    return metaDictionary;
}

- (void)setDelegate:(id)value
{
    delegate = value;
}

270 271
- (id)delegate
{
272
    return delegate;
273 274 275 276
}
@end

@implementation VLCMedia (LibVLCBridging)
277 278 279

+ (id)mediaWithLibVLCMediaDescriptor:(void *)md
{
280
    return [[[VLCMedia alloc] initWithLibVLCMediaDescriptor:md] autorelease];
281 282 283
}

- (id)initWithLibVLCMediaDescriptor:(void *)md
284 285 286
{
    if (self = [super init])
    {
287 288
        libvlc_exception_t ex;
        libvlc_exception_init( &ex );
289
        char * p_url;
290
        
291
        p_url = libvlc_media_descriptor_get_mrl( md, &ex );
292
        quit_on_exception( &ex );
293
        
294
        url = [[NSString stringWithCString:p_url] retain];
295
        
296
        libvlc_media_descriptor_retain( md );
297 298 299
        p_md = md;
        
        [self initInternalMediaDescriptor];
300 301 302 303
    }
    return self;
}

304
- (void *)libVLCMediaDescriptor
305
{
306
    return p_md;
307
}
308 309
@end

310
@implementation VLCMedia (Private)
311 312
+ (libvlc_meta_t)stringToMetaType:(NSString *)string
{
313
#define VLCStringToMeta( name, string ) if ([VLCMetaInformation##name compare:string] == NSOrderedSame) return libvlc_meta_##name;
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    VLCStringToMeta(Title, string);
    VLCStringToMeta(Artist, string);
    VLCStringToMeta(Genre, string);
    VLCStringToMeta(Copyright, string);
    VLCStringToMeta(Album, string);
    VLCStringToMeta(TrackNumber, string);
    VLCStringToMeta(Description, string);
    VLCStringToMeta(Rating, string);
    VLCStringToMeta(Date, string);
    VLCStringToMeta(Setting, string);
    VLCStringToMeta(URL, string);
    VLCStringToMeta(Language, string);
    VLCStringToMeta(NowPlaying, string);
    VLCStringToMeta(Publisher, string);
    VLCStringToMeta(ArtworkURL, string);
    VLCStringToMeta(TrackID, string);
330
#undef VLCStringToMeta
331 332 333 334 335
    return -1;
}

+ (NSString *)metaTypeToString:(libvlc_meta_t)type
{
336
#define VLCMetaToString( name, type )   if (libvlc_meta_##name == type) return VLCMetaInformation##name;
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    VLCMetaToString(Title, type);
    VLCMetaToString(Artist, type);
    VLCMetaToString(Genre, type);
    VLCMetaToString(Copyright, type);
    VLCMetaToString(Album, type);
    VLCMetaToString(TrackNumber, type);
    VLCMetaToString(Description, type);
    VLCMetaToString(Rating, type);
    VLCMetaToString(Date, type);
    VLCMetaToString(Setting, type);
    VLCMetaToString(URL, type);
    VLCMetaToString(Language, type);
    VLCMetaToString(NowPlaying, type);
    VLCMetaToString(Publisher, type);
    VLCMetaToString(ArtworkURL, type);
    VLCMetaToString(TrackID, type);
353
#undef VLCMetaToString
354 355 356 357
    return nil;
}

- (void)initInternalMediaDescriptor
358
{
359
    libvlc_exception_t ex;
360 361 362 363
    libvlc_exception_init( &ex );

    libvlc_media_descriptor_set_user_data( p_md, (void*)self, &ex );
    quit_on_exception( &ex );
364 365
    
    // TODO: Should these events be caught by VLCMediaList's notification hooks?
366
    libvlc_event_manager_t *p_em = libvlc_media_descriptor_event_manager( p_md, &ex );
367 368
//    libvlc_event_attach(p_em, libvlc_MediaDescriptorSubItemAdded,    HandleMediaSubItemAdded,    self, &ex);
//    libvlc_event_attach(p_em, libvlc_MediaDescriptorSubItemRemoved,  HandleMediaSubItemRemoved,  self, &ex);
369 370
    libvlc_event_attach(p_em, libvlc_MediaDescriptorMetaChanged,     HandleMediaMetaChanged,     self, &ex);
    libvlc_event_attach(p_em, libvlc_MediaDescriptorDurationChanged, HandleMediaDurationChanged, self, &ex);
371
    quit_on_exception( &ex );
372
    
373
    libvlc_media_list_t *p_mlist = libvlc_media_descriptor_subitems( p_md, NULL );
374 375 376 377 378
    if (!p_mlist)
        subitems = nil;
    else
    {
        [subitems release];
379
        subitems = [[VLCMediaList mediaListWithLibVLCMediaList:p_mlist] retain];
380
        libvlc_media_list_release( p_mlist );
381 382
    }
    [self fetchMetaInformation];
383
}
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

- (BOOL)setMetaValue:(char *)value forKey:(NSString *)key
{
    BOOL result = NO;
    
    NSString *oldValue = [metaDictionary valueForKey:key];
    if ((!oldValue && value) || (oldValue && !value) || (oldValue && value && [oldValue compare:[NSString stringWithCString:value]] != NSOrderedSame))
    {
        if (!metaDictionary)
            metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];

        if (value)
            [metaDictionary setValue:[NSString stringWithCString:value] forKeyPath:key];
        else
            [metaDictionary setValue:nil forKeyPath:key];
        
        if ([key compare:VLCMetaInformationArtworkURL] == NSOrderedSame)
        {
            if ([metaDictionary valueForKey:VLCMetaInformationArtworkURL])
            {
                // Initialize a new thread
                [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:) 
                                         toTarget:self
                                       withObject:[metaDictionary valueForKey:VLCMetaInformationArtworkURL]];
            }
        }
        result = YES;
    }
412
    free( value );
413 414 415 416 417 418 419 420
    return result;
}

- (void)fetchMetaInformation
{
    // TODO: Only fetch meta data that has been requested.  Just don't fetch
    // it, just because.
    
421 422 423
    [self setMetaValue:libvlc_media_descriptor_get_meta( p_md, libvlc_meta_Title,      NULL ) forKey:[VLCMedia metaTypeToString:libvlc_meta_Title]];
    [self setMetaValue:libvlc_media_descriptor_get_meta( p_md, libvlc_meta_Artist,     NULL ) forKey:[VLCMedia metaTypeToString:libvlc_meta_Artist]];
    [self setMetaValue:libvlc_media_descriptor_get_meta( p_md, libvlc_meta_ArtworkURL, NULL ) forKey:[VLCMedia metaTypeToString:libvlc_meta_ArtworkURL]];
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
}

- (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    @try
    {
        // Go ahead and load up the art work
        NSURL *artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSImage *art  = [[[NSImage alloc] initWithContentsOfURL:artUrl] autorelease]; 
        
        // If anything was found, lets save it to the meta data dictionary
        if (art)
        {
            @synchronized(metaDictionary)
            {
                [metaDictionary setObject:art forKey:VLCMetaInformationArtwork];
            }
            
            // Let the world know that there is new art work available
            [self notifyChangeForKey:VLCMetaInformationArtwork withOldValue:nil];
        }
    }
    @finally 
    {
        [pool release];
    }
}

- (void)notifyChangeForKey:(NSString *)key withOldValue:(id)oldValue
{
    // Send out a formal notification
    [[NSNotificationCenter defaultCenter] postNotificationName:VLCMediaMetaChanged
                                                        object:self
                                                      userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
                                                          key, @"key",
                                                          oldValue, @"oldValue", 
                                                          nil]];
    
    // Now notify the delegate
    if (delegate && [delegate respondsToSelector:@selector(media:metaValueChangedFrom:forKey:)])
        [delegate media:self metaValueChangedFrom:oldValue forKey:key];
}

//- (void)subItemAdded:(libvlc_media_descriptor_t *)child
//{
//  // TODO: SubItemAdded Notification
////    if (!subitems)
////    {
////        subitems = [[VLCMediaList alloc] initWithLibVLCMediaList:];
////    }
//}
//
//- (void)subItemRemoved:(libvlc_media_descriptor_t *)child
//{
//  // TODO: SubItemAdded Notification
//  //    if (!subitems)
//  //    {
//  //      subitems = [[VLCMediaList alloc] initWithLibVLCMediaList:];
//  //    }
//}

- (void)metaChanged:(NSNumber *)metaType
{
    // TODO: Only retrieve the meta that was changed
    // Can we figure out what piece was changed instead of retreiving everything?
    NSString *key = [VLCMedia metaTypeToString:[metaType intValue]];
    id oldValue = (metaDictionary ? [metaDictionary valueForKey:key] : nil);

    // Update the meta data
    if ([self setMetaValue:libvlc_media_descriptor_get_meta(p_md, [metaType intValue], NULL) forKey:key])
        // There was actually a change, send out the notifications
        [self notifyChangeForKey:key withOldValue:oldValue];
}
@end

@implementation VLCMedia (VLCMediaPlayerBridging)

- (void)setLength:(VLCTime *)value
{
    if (length != value)
    {
        if (length && value && [length compare:value] == NSOrderedSame)
            return;
        
        [self willChangeValueForKey:@"length"];

        if (length) {
            [length release];
            length = nil;
        }
        
        if (value)
            length = [value retain];

        [self didChangeValueForKey:@"length"];
    }
}
@end