VLCMedia.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. /*****************************************************************************
  2. * VLCMedia.m: VLC.framework VLCMedia 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. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 2 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  23. *****************************************************************************/
  24. #import "VLCMedia.h"
  25. #import "VLCMediaList.h"
  26. #import "VLCEventManager.h"
  27. #import "VLCLibrary.h"
  28. #import "VLCLibVLCBridging.h"
  29. #include <vlc/libvlc.h>
  30. /* Meta Dictionary Keys */
  31. NSString *VLCMetaInformationTitle = @"title";
  32. NSString *VLCMetaInformationArtist = @"artist";
  33. NSString *VLCMetaInformationGenre = @"genre";
  34. NSString *VLCMetaInformationCopyright = @"copyright";
  35. NSString *VLCMetaInformationAlbum = @"album";
  36. NSString *VLCMetaInformationTrackNumber = @"trackNumber";
  37. NSString *VLCMetaInformationDescription = @"description";
  38. NSString *VLCMetaInformationRating = @"rating";
  39. NSString *VLCMetaInformationDate = @"date";
  40. NSString *VLCMetaInformationSetting = @"setting";
  41. NSString *VLCMetaInformationURL = @"url";
  42. NSString *VLCMetaInformationLanguage = @"language";
  43. NSString *VLCMetaInformationNowPlaying = @"nowPlaying";
  44. NSString *VLCMetaInformationPublisher = @"publisher";
  45. NSString *VLCMetaInformationEncodedBy = @"encodedBy";
  46. NSString *VLCMetaInformationArtworkURL = @"artworkURL";
  47. NSString *VLCMetaInformationArtwork = @"artwork";
  48. NSString *VLCMetaInformationTrackID = @"trackID";
  49. /* Notification Messages */
  50. NSString *VLCMediaMetaChanged = @"VLCMediaMetaChanged";
  51. //NSString *VLCMediaSubItemAdded = @"VLCMediaSubItemAdded";
  52. //NSString *VLCMediaSubItemDeleted = @"VLCMediaSubItemDeleted";
  53. /* libvlc event callback */
  54. //static void HandleMediaSubItemAdded(const libvlc_event_t *event, void *self)
  55. //{
  56. // [[VLCEventManager sharedManager] callOnMainThreadObject:self
  57. // withMethod:@selector(subItemAdded:)
  58. // withArgumentAsObject:(id)event->u.media_descriptor_subitem_added.new_child];
  59. //}
  60. //
  61. //static void HandleMediaSubItemDeleted(const libvlc_event_t *event, void *self)
  62. //{
  63. // [[VLCEventManager sharedManager] callOnMainThreadObject:self
  64. // withMethod:@selector(subItemDeleted)
  65. // withArgumentAsObject:nil];
  66. //}
  67. static void HandleMediaMetaChanged(const libvlc_event_t *event, void *self)
  68. {
  69. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  70. [[VLCEventManager sharedManager] callOnMainThreadObject:self
  71. withMethod:@selector(metaChanged:)
  72. withArgumentAsObject:[NSNumber numberWithInt:(int)event->u.media_descriptor_meta_changed.meta_type]];
  73. [pool release];
  74. }
  75. static void HandleMediaDurationChanged(const libvlc_event_t *event, void *self)
  76. {
  77. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  78. //[[VLCEventManager sharedManager] callOnMainThreadObject:self
  79. // withMethod:@selector(setLength:)
  80. // withArgumentAsObject:[VLCTime timeWithNumber:
  81. // [NSNumber numberWithLongLong:event->u.media_descriptor_duration_changed.new_duration]]];
  82. [pool release];
  83. }
  84. // TODO: Documentation
  85. @interface VLCMedia (Private)
  86. /* Statics */
  87. + (libvlc_meta_t)stringToMetaType:(NSString *)string;
  88. + (NSString *)metaTypeToString:(libvlc_meta_t)type;
  89. /* Initializers */
  90. - (void)initInternalMediaDescriptor;
  91. /* Operations */
  92. - (BOOL)setMetaValue:(char *)value forKey:(NSString *)key;
  93. - (void)fetchMetaInformation;
  94. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL;
  95. - (void)notifyChangeForKey:(NSString *)key withOldValue:(id)oldValue;
  96. /* Callback Methods */
  97. //- (void)subItemAdded:(libvlc_media_descriptor_t *)child;
  98. //- (void)subItemRemoved:(libvlc_media_descriptor_t *)child;
  99. - (void)metaChanged:(NSNumber *)metaType;
  100. @end
  101. @implementation VLCMedia
  102. + (id)mediaWithURL:(NSString *)aURL;
  103. {
  104. // For some unknown reason, compiler kept shooting me a warning saying:
  105. // warning: passing argument 1 of 'initWithURL:' from distinct Objective-C type
  106. // Research on the net shows that the error means that the argument passed
  107. // is not compatible with the expected argument. Doesn't make sense, however
  108. // the warning goes away when it is casted it with "id".
  109. return [[[VLCMedia alloc] initWithURL:(id)aURL] autorelease];
  110. }
  111. - (id)initWithURL:(NSString *)aURL
  112. {
  113. // Parse the URL
  114. NSString *scheme; // Everything before ://, defaults to file if not present
  115. NSString *path; // Everything after ://
  116. NSRange range;
  117. range = [aURL rangeOfString:@"://"];
  118. if (range.length > 0)
  119. {
  120. scheme = [aURL substringToIndex:range.location];
  121. }
  122. else
  123. {
  124. scheme = @"file";
  125. range.location = 0;
  126. }
  127. path = [aURL substringFromIndex:NSMaxRange(range)];
  128. if ([scheme isEqualToString:@"file"])
  129. {
  130. BOOL isDirectory;
  131. path = [path stringByExpandingTildeInPath];
  132. // Check to see if it's a file or url
  133. NSString *videoTSPath = path;
  134. if ([[NSFileManager defaultManager] fileExistsAtPath:videoTSPath isDirectory:&isDirectory] && isDirectory)
  135. {
  136. if ([[videoTSPath lastPathComponent] compare:@"VIDEO_TS"] != NSOrderedSame)
  137. videoTSPath = [videoTSPath stringByAppendingPathComponent:@"VIDEO_TS/"];
  138. videoTSPath = [videoTSPath stringByAppendingPathComponent:@"VIDEO_TS.VOB"];
  139. // The url is a directory should we check for a DVD directory structure?
  140. if ([[NSFileManager defaultManager] fileExistsAtPath:videoTSPath isDirectory:&isDirectory] && !isDirectory)
  141. /* do nothing because this is a DVD */;
  142. else
  143. // TODO: Should we search for playable items?
  144. // This is not a playable file
  145. return nil;
  146. }
  147. }
  148. if (self = [super init])
  149. {
  150. url = [[NSString stringWithFormat:@"%@://%@", scheme, path] retain];
  151. libvlc_exception_t ex;
  152. libvlc_exception_init(&ex);
  153. p_md = libvlc_media_descriptor_new([VLCLibrary sharedInstance],
  154. [url cString],
  155. &ex);
  156. quit_on_exception(&ex);
  157. delegate = nil;
  158. metaDictionary = nil;
  159. // This value is set whenever the demuxer figures out what the length is.
  160. // TODO: Easy way to tell the length of the movie without having to instiate the demuxer. Maybe cached info?
  161. length = nil;
  162. [self initInternalMediaDescriptor];
  163. }
  164. return self;
  165. }
  166. - (void)release
  167. {
  168. @synchronized(self)
  169. {
  170. if([self retainCount] <= 1)
  171. {
  172. /* We must make sure we won't receive new event after an upcoming dealloc
  173. * We also may receive a -retain in some event callback that may occcur
  174. * Before libvlc_event_detach. So this can't happen in dealloc */
  175. libvlc_event_manager_t *p_em = libvlc_media_descriptor_event_manager(p_md, NULL);
  176. // libvlc_event_detach(p_em, libvlc_MediaDescriptorSubItemAdded, HandleMediaSubItemAdded, self, NULL);
  177. // libvlc_event_detach(p_em, libvlc_MediaDescriptorSubItemDeleted, HandleMediaSubItemAdded, self, NULL);
  178. // libvlc_event_detach(p_em, libvlc_MediaDescriptorMetaChanged, HandleMediaMetaChanged, self, NULL);
  179. // libvlc_event_detach(p_em, libvlc_MediaDescriptorDurationChanged, HandleMediaDurationChanged, self, NULL);
  180. }
  181. [super release];
  182. }
  183. }
  184. - (void)dealloc
  185. {
  186. // Testing to see if the pointer exists is not required, if the pointer is null
  187. // then the release message is not sent to it.
  188. [self setDelegate:nil];
  189. [self setLength:nil];
  190. [url release];
  191. [subitems release];
  192. [metaDictionary release];
  193. libvlc_media_descriptor_release( p_md );
  194. [super dealloc];
  195. }
  196. - (NSString *)description
  197. {
  198. NSString *result = nil;
  199. if (metaDictionary)
  200. result = [metaDictionary objectForKey:VLCMetaInformationTitle];
  201. return (result ? result : url);
  202. }
  203. - (NSComparisonResult)compare:(VLCMedia *)media
  204. {
  205. if (self == media)
  206. return NSOrderedSame;
  207. else if (!media)
  208. return NSOrderedDescending;
  209. else
  210. return [[self url] compare:[media url]];
  211. }
  212. - (NSString *)url
  213. {
  214. return [[url copy] autorelease];
  215. }
  216. - (VLCMediaList *)subitems
  217. {
  218. return subitems;
  219. }
  220. - (VLCTime *)length
  221. {
  222. if (!length)
  223. {
  224. // Try figuring out what the length is
  225. long long duration = libvlc_media_descriptor_get_duration( p_md, NULL );
  226. if (duration > -1)
  227. {
  228. [self setLength:[VLCTime timeWithNumber:[NSNumber numberWithLongLong:duration]]];
  229. return [[length retain] autorelease];
  230. }
  231. }
  232. return [VLCTime nullTime];
  233. }
  234. - (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
  235. {
  236. #define CLOCK_FREQ 1000000
  237. #define THREAD_SLEEP ((long long)(0.010*CLOCK_FREQ))
  238. if (![url hasPrefix:@"file://"])
  239. return [self length];
  240. else if (!length)
  241. {
  242. while (!length && ![self isPreparsed] && [aDate timeIntervalSinceNow] > 0)
  243. {
  244. usleep( THREAD_SLEEP );
  245. }
  246. // So we're done waiting, but sometimes we trap the fact that the parsing
  247. // was done before the length gets assigned, so lets go ahead and assign
  248. // it ourselves.
  249. if (!length)
  250. return [self length];
  251. }
  252. #undef CLOCK_FREQ
  253. #undef THREAD_SLEEP
  254. return [[length retain] autorelease];
  255. }
  256. - (BOOL)isPreparsed
  257. {
  258. return libvlc_media_descriptor_is_preparsed( p_md, NULL );
  259. }
  260. - (NSDictionary *)metaDictionary
  261. {
  262. return metaDictionary;
  263. }
  264. - (void)setDelegate:(id)value
  265. {
  266. delegate = value;
  267. }
  268. - (id)delegate
  269. {
  270. return delegate;
  271. }
  272. @end
  273. @implementation VLCMedia (LibVLCBridging)
  274. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  275. {
  276. libvlc_exception_t ex;
  277. libvlc_exception_init( &ex );
  278. VLCMedia *media = (VLCMedia *)libvlc_media_descriptor_get_user_data( md, &ex );
  279. if (!media || libvlc_exception_raised( &ex ))
  280. {
  281. libvlc_exception_clear( &ex );
  282. return [[[VLCMedia alloc] initWithLibVLCMediaDescriptor:md] autorelease];
  283. }
  284. else
  285. {
  286. return media;
  287. }
  288. }
  289. - (id)initWithLibVLCMediaDescriptor:(void *)md
  290. {
  291. libvlc_exception_t ex;
  292. libvlc_exception_init( &ex );
  293. // Core hacks that allows for native objects to be paired with core objects. Otherwise, a native object
  294. // would be recreated every time we want to address the media descriptor. This eliminates the need
  295. // for maintaining local copies of core objects.
  296. if ((self = (id)libvlc_media_descriptor_get_user_data(md, &ex)) && !libvlc_exception_raised(&ex))
  297. {
  298. return [self retain];
  299. }
  300. libvlc_exception_clear( &ex ); // Just in case an exception was raised, lets release it
  301. if (self = [super init])
  302. {
  303. char * p_url;
  304. p_url = libvlc_media_descriptor_get_mrl( md, &ex );
  305. quit_on_exception( &ex );
  306. url = [NSString stringWithCString:p_url];
  307. libvlc_media_descriptor_retain( md );
  308. p_md = md;
  309. [self initInternalMediaDescriptor];
  310. }
  311. return self;
  312. }
  313. - (void *)libVLCMediaDescriptor
  314. {
  315. return p_md;
  316. }
  317. @end
  318. @implementation VLCMedia (Private)
  319. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  320. {
  321. #define VLCStringToMeta( name, string ) if ([VLCMetaInformation##name compare:string] == NSOrderedSame) return libvlc_meta_##name;
  322. VLCStringToMeta(Title, string);
  323. VLCStringToMeta(Artist, string);
  324. VLCStringToMeta(Genre, string);
  325. VLCStringToMeta(Copyright, string);
  326. VLCStringToMeta(Album, string);
  327. VLCStringToMeta(TrackNumber, string);
  328. VLCStringToMeta(Description, string);
  329. VLCStringToMeta(Rating, string);
  330. VLCStringToMeta(Date, string);
  331. VLCStringToMeta(Setting, string);
  332. VLCStringToMeta(URL, string);
  333. VLCStringToMeta(Language, string);
  334. VLCStringToMeta(NowPlaying, string);
  335. VLCStringToMeta(Publisher, string);
  336. VLCStringToMeta(ArtworkURL, string);
  337. VLCStringToMeta(TrackID, string);
  338. #undef VLCStringToMeta
  339. return -1;
  340. }
  341. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  342. {
  343. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  344. VLCMetaToString(Title, type);
  345. VLCMetaToString(Artist, type);
  346. VLCMetaToString(Genre, type);
  347. VLCMetaToString(Copyright, type);
  348. VLCMetaToString(Album, type);
  349. VLCMetaToString(TrackNumber, type);
  350. VLCMetaToString(Description, type);
  351. VLCMetaToString(Rating, type);
  352. VLCMetaToString(Date, type);
  353. VLCMetaToString(Setting, type);
  354. VLCMetaToString(URL, type);
  355. VLCMetaToString(Language, type);
  356. VLCMetaToString(NowPlaying, type);
  357. VLCMetaToString(Publisher, type);
  358. VLCMetaToString(ArtworkURL, type);
  359. VLCMetaToString(TrackID, type);
  360. #undef VLCMetaToString
  361. return nil;
  362. }
  363. - (void)initInternalMediaDescriptor
  364. {
  365. libvlc_exception_t ex;
  366. libvlc_exception_init( &ex );
  367. libvlc_media_descriptor_set_user_data( p_md, (void*)self, &ex );
  368. quit_on_exception( &ex );
  369. // TODO: Should these events be caught by VLCMediaList's notification hooks?
  370. libvlc_event_manager_t *p_em = libvlc_media_descriptor_event_manager( p_md, &ex );
  371. // libvlc_event_attach(p_em, libvlc_MediaDescriptorSubItemAdded, HandleMediaSubItemAdded, self, &ex);
  372. // libvlc_event_attach(p_em, libvlc_MediaDescriptorSubItemRemoved, HandleMediaSubItemRemoved, self, &ex);
  373. // libvlc_event_attach(p_em, libvlc_MediaDescriptorMetaChanged, HandleMediaMetaChanged, self, &ex);
  374. // libvlc_event_attach(p_em, libvlc_MediaDescriptorDurationChanged, HandleMediaDurationChanged, self, &ex);
  375. quit_on_exception( &ex );
  376. libvlc_media_list_t *p_mlist = libvlc_media_descriptor_subitems( p_md, NULL );
  377. if (!p_mlist)
  378. subitems = nil;
  379. else
  380. {
  381. [subitems release];
  382. subitems = [[VLCMediaList medialistWithLibVLCMediaList:p_mlist] retain];
  383. libvlc_media_list_release( p_mlist );
  384. }
  385. [self fetchMetaInformation];
  386. }
  387. - (BOOL)setMetaValue:(char *)value forKey:(NSString *)key
  388. {
  389. BOOL result = NO;
  390. NSString *oldValue = [metaDictionary valueForKey:key];
  391. if ((!oldValue && value) || (oldValue && !value) || (oldValue && value && [oldValue compare:[NSString stringWithCString:value]] != NSOrderedSame))
  392. {
  393. if (!metaDictionary)
  394. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  395. if (value)
  396. [metaDictionary setValue:[NSString stringWithCString:value] forKeyPath:key];
  397. else
  398. [metaDictionary setValue:nil forKeyPath:key];
  399. if ([key compare:VLCMetaInformationArtworkURL] == NSOrderedSame)
  400. {
  401. if ([metaDictionary valueForKey:VLCMetaInformationArtworkURL])
  402. {
  403. // Initialize a new thread
  404. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  405. toTarget:self
  406. withObject:[metaDictionary valueForKey:VLCMetaInformationArtworkURL]];
  407. }
  408. }
  409. result = YES;
  410. }
  411. free( value );
  412. return result;
  413. }
  414. - (void)fetchMetaInformation
  415. {
  416. // TODO: Only fetch meta data that has been requested. Just don't fetch
  417. // it, just because.
  418. [self setMetaValue:libvlc_media_descriptor_get_meta( p_md, libvlc_meta_Title, NULL ) forKey:[VLCMedia metaTypeToString:libvlc_meta_Title]];
  419. [self setMetaValue:libvlc_media_descriptor_get_meta( p_md, libvlc_meta_Artist, NULL ) forKey:[VLCMedia metaTypeToString:libvlc_meta_Artist]];
  420. [self setMetaValue:libvlc_media_descriptor_get_meta( p_md, libvlc_meta_ArtworkURL, NULL ) forKey:[VLCMedia metaTypeToString:libvlc_meta_ArtworkURL]];
  421. }
  422. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  423. {
  424. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  425. @try
  426. {
  427. // Go ahead and load up the art work
  428. NSURL *artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  429. NSImage *art = [[[NSImage alloc] initWithContentsOfURL:artUrl] autorelease];
  430. // If anything was found, lets save it to the meta data dictionary
  431. if (art)
  432. {
  433. @synchronized(metaDictionary)
  434. {
  435. [metaDictionary setObject:art forKey:VLCMetaInformationArtwork];
  436. }
  437. // Let the world know that there is new art work available
  438. [self notifyChangeForKey:VLCMetaInformationArtwork withOldValue:nil];
  439. }
  440. }
  441. @finally
  442. {
  443. [pool release];
  444. }
  445. }
  446. - (void)notifyChangeForKey:(NSString *)key withOldValue:(id)oldValue
  447. {
  448. // Send out a formal notification
  449. [[NSNotificationCenter defaultCenter] postNotificationName:VLCMediaMetaChanged
  450. object:self
  451. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
  452. key, @"key",
  453. oldValue, @"oldValue",
  454. nil]];
  455. // Now notify the delegate
  456. if (delegate && [delegate respondsToSelector:@selector(media:metaValueChangedFrom:forKey:)])
  457. [delegate media:self metaValueChangedFrom:oldValue forKey:key];
  458. }
  459. //- (void)subItemAdded:(libvlc_media_descriptor_t *)child
  460. //{
  461. // // TODO: SubItemAdded Notification
  462. //// if (!subitems)
  463. //// {
  464. //// subitems = [[VLCMediaList alloc] initWithLibVLCMediaList:];
  465. //// }
  466. //}
  467. //
  468. //- (void)subItemRemoved:(libvlc_media_descriptor_t *)child
  469. //{
  470. // // TODO: SubItemAdded Notification
  471. // // if (!subitems)
  472. // // {
  473. // // subitems = [[VLCMediaList alloc] initWithLibVLCMediaList:];
  474. // // }
  475. //}
  476. - (void)metaChanged:(NSNumber *)metaType
  477. {
  478. // TODO: Only retrieve the meta that was changed
  479. // Can we figure out what piece was changed instead of retreiving everything?
  480. NSString *key = [VLCMedia metaTypeToString:[metaType intValue]];
  481. id oldValue = (metaDictionary ? [metaDictionary valueForKey:key] : nil);
  482. // Update the meta data
  483. if ([self setMetaValue:libvlc_media_descriptor_get_meta(p_md, [metaType intValue], NULL) forKey:key])
  484. // There was actually a change, send out the notifications
  485. [self notifyChangeForKey:key withOldValue:oldValue];
  486. }
  487. @end
  488. @implementation VLCMedia (VLCMediaPlayerBridging)
  489. - (void)setLength:(VLCTime *)value
  490. {
  491. if (length != value)
  492. {
  493. if (length && value && [length compare:value] == NSOrderedSame)
  494. return;
  495. [self willChangeValueForKey:@"length"];
  496. if (length) {
  497. [length release];
  498. length = nil;
  499. }
  500. if (value)
  501. length = [value retain];
  502. [self didChangeValueForKey:@"length"];
  503. }
  504. }
  505. @end