VLCMedia.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /*****************************************************************************
  2. * VLCMedia.m: VLCKit.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. /******************************************************************************
  52. * @property (readwrite)
  53. */
  54. @interface VLCMedia ()
  55. @property (readwrite) VLCMediaState state;
  56. @end
  57. /******************************************************************************
  58. * Interface (Private)
  59. */
  60. // TODO: Documentation
  61. @interface VLCMedia (Private)
  62. /* Statics */
  63. + (libvlc_meta_t)stringToMetaType:(NSString *)string;
  64. + (NSString *)metaTypeToString:(libvlc_meta_t)type;
  65. /* Initializers */
  66. - (void)initInternalMediaDescriptor;
  67. /* Operations */
  68. - (void)fetchMetaInformationFromLibVLCWithType:(NSString*)metaType;
  69. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL;
  70. - (void)setArtwork:(NSImage *)art;
  71. /* Callback Methods */
  72. - (void)metaChanged:(NSString *)metaType;
  73. - (void)subItemAdded;
  74. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber;
  75. @end
  76. static VLCMediaState libvlc_state_to_media_state[] =
  77. {
  78. [libvlc_NothingSpecial] = VLCMediaStateNothingSpecial,
  79. [libvlc_Stopped] = VLCMediaStateNothingSpecial,
  80. [libvlc_Opening] = VLCMediaStateNothingSpecial,
  81. [libvlc_Buffering] = VLCMediaStateBuffering,
  82. [libvlc_Ended] = VLCMediaStateNothingSpecial,
  83. [libvlc_Error] = VLCMediaStateError,
  84. [libvlc_Playing] = VLCMediaStatePlaying,
  85. [libvlc_Paused] = VLCMediaStatePlaying,
  86. };
  87. static inline VLCMediaState LibVLCStateToMediaState( libvlc_state_t state )
  88. {
  89. return libvlc_state_to_media_state[state];
  90. }
  91. /******************************************************************************
  92. * LibVLC Event Callback
  93. */
  94. static void HandleMediaMetaChanged(const libvlc_event_t * event, void * self)
  95. {
  96. if( event->u.media_meta_changed.meta_type == libvlc_meta_Publisher ||
  97. event->u.media_meta_changed.meta_type == libvlc_meta_NowPlaying )
  98. {
  99. /* Skip those meta. We don't really care about them for now.
  100. * And they occure a lot */
  101. return;
  102. }
  103. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  104. [[VLCEventManager sharedManager] callOnMainThreadObject:self
  105. withMethod:@selector(metaChanged:)
  106. withArgumentAsObject:[VLCMedia metaTypeToString:event->u.media_meta_changed.meta_type]];
  107. [pool release];
  108. }
  109. static void HandleMediaDurationChanged(const libvlc_event_t * event, void * self)
  110. {
  111. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  112. [[VLCEventManager sharedManager] callOnMainThreadObject:self
  113. withMethod:@selector(setLength:)
  114. withArgumentAsObject:[VLCTime timeWithNumber:
  115. [NSNumber numberWithLongLong:event->u.media_duration_changed.new_duration]]];
  116. [pool release];
  117. }
  118. static void HandleMediaStateChanged(const libvlc_event_t * event, void * self)
  119. {
  120. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  121. [[VLCEventManager sharedManager] callOnMainThreadObject:self
  122. withMethod:@selector(setStateAsNumber:)
  123. withArgumentAsObject:[NSNumber numberWithInt:
  124. LibVLCStateToMediaState(event->u.media_state_changed.new_state)]];
  125. [pool release];
  126. }
  127. static void HandleMediaSubItemAdded(const libvlc_event_t * event, void * self)
  128. {
  129. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  130. [[VLCEventManager sharedManager] callOnMainThreadObject:self
  131. withMethod:@selector(subItemAdded)
  132. withArgumentAsObject:nil];
  133. [pool release];
  134. }
  135. /******************************************************************************
  136. * Implementation
  137. */
  138. @implementation VLCMedia
  139. + (id)mediaWithURL:(NSURL *)anURL;
  140. {
  141. return [[[VLCMedia alloc] initWithURL:anURL] autorelease];
  142. }
  143. + (id)mediaWithPath:(NSString *)aPath;
  144. {
  145. return [[[VLCMedia alloc] initWithPath:aPath] autorelease];
  146. }
  147. + (id)mediaAsNodeWithName:(NSString *)aName;
  148. {
  149. return [[[VLCMedia alloc] initAsNodeWithName:aName] autorelease];
  150. }
  151. - (id)initWithPath:(NSString *)aPath
  152. {
  153. return [self initWithURL:[NSURL fileURLWithPath:aPath isDirectory:NO]];
  154. }
  155. - (id)initWithURL:(NSURL *)anURL
  156. {
  157. if (self = [super init])
  158. {
  159. p_md = libvlc_media_new_location([VLCLibrary sharedInstance],
  160. [[anURL absoluteString] UTF8String]);
  161. delegate = nil;
  162. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  163. // This value is set whenever the demuxer figures out what the length is.
  164. // TODO: Easy way to tell the length of the movie without having to instiate the demuxer. Maybe cached info?
  165. length = nil;
  166. [self initInternalMediaDescriptor];
  167. }
  168. return self;
  169. }
  170. - (id)initAsNodeWithName:(NSString *)aName
  171. {
  172. if (self = [super init])
  173. {
  174. p_md = libvlc_media_new_as_node([VLCLibrary sharedInstance],
  175. [aName UTF8String]);
  176. delegate = nil;
  177. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  178. // This value is set whenever the demuxer figures out what the length is.
  179. // TODO: Easy way to tell the length of the movie without having to instiate the demuxer. Maybe cached info?
  180. length = nil;
  181. [self initInternalMediaDescriptor];
  182. }
  183. return self;
  184. }
  185. - (void)release
  186. {
  187. @synchronized(self)
  188. {
  189. if([self retainCount] <= 1)
  190. {
  191. /* We must make sure we won't receive new event after an upcoming dealloc
  192. * We also may receive a -retain in some event callback that may occcur
  193. * Before libvlc_event_detach. So this can't happen in dealloc */
  194. libvlc_event_manager_t * p_em = libvlc_media_event_manager(p_md);
  195. libvlc_event_detach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, self);
  196. libvlc_event_detach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, self);
  197. libvlc_event_detach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, self);
  198. libvlc_event_detach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, self);
  199. }
  200. [super release];
  201. }
  202. }
  203. - (void)dealloc
  204. {
  205. // Testing to see if the pointer exists is not required, if the pointer is null
  206. // then the release message is not sent to it.
  207. delegate = nil;
  208. [length release];
  209. [url release];
  210. [subitems release];
  211. [metaDictionary release];
  212. libvlc_media_release( p_md );
  213. [super dealloc];
  214. }
  215. - (NSString *)description
  216. {
  217. NSString * result = [metaDictionary objectForKey:VLCMetaInformationTitle];
  218. return [NSString stringWithFormat:@"<%@ %p> %@", [self className], self, (result ? result : [url absoluteString])];
  219. }
  220. - (NSComparisonResult)compare:(VLCMedia *)media
  221. {
  222. if (self == media)
  223. return NSOrderedSame;
  224. if (!media)
  225. return NSOrderedDescending;
  226. return p_md == [media libVLCMediaDescriptor] ? NSOrderedSame : NSOrderedAscending;
  227. }
  228. @synthesize delegate;
  229. - (VLCTime *)length
  230. {
  231. if (!length)
  232. {
  233. // Try figuring out what the length is
  234. long long duration = libvlc_media_get_duration( p_md );
  235. if (duration > -1)
  236. {
  237. length = [[VLCTime timeWithNumber:[NSNumber numberWithLongLong:duration]] retain];
  238. return [[length retain] autorelease];
  239. }
  240. return [VLCTime nullTime];
  241. }
  242. return [[length retain] autorelease];
  243. }
  244. - (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
  245. {
  246. static const long long thread_sleep = 10000;
  247. if (!length)
  248. {
  249. // Force preparsing of this item.
  250. [self length];
  251. // wait until we are preparsed
  252. while (!length && ![self isPreparsed] && [aDate timeIntervalSinceNow] > 0)
  253. {
  254. usleep( thread_sleep );
  255. }
  256. // So we're done waiting, but sometimes we trap the fact that the parsing
  257. // was done before the length gets assigned, so lets go ahead and assign
  258. // it ourselves.
  259. if (!length)
  260. return [self length];
  261. }
  262. return [[length retain] autorelease];
  263. }
  264. - (BOOL)isPreparsed
  265. {
  266. return libvlc_media_is_preparsed( p_md );
  267. }
  268. @synthesize url;
  269. @synthesize subitems;
  270. @synthesize metaDictionary;
  271. @synthesize state;
  272. @end
  273. /******************************************************************************
  274. * Implementation VLCMedia (LibVLCBridging)
  275. */
  276. @implementation VLCMedia (LibVLCBridging)
  277. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  278. {
  279. return [[[VLCMedia alloc] initWithLibVLCMediaDescriptor:md] autorelease];
  280. }
  281. - (id)initWithLibVLCMediaDescriptor:(void *)md
  282. {
  283. if (self = [super init])
  284. {
  285. libvlc_media_retain( md );
  286. p_md = md;
  287. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  288. [self initInternalMediaDescriptor];
  289. }
  290. return self;
  291. }
  292. - (void *)libVLCMediaDescriptor
  293. {
  294. return p_md;
  295. }
  296. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  297. {
  298. libvlc_media_t * p_md;
  299. p_md = libvlc_media_duplicate( [media libVLCMediaDescriptor] );
  300. for( NSString * key in [options allKeys] )
  301. {
  302. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=#%@", key, [options objectForKey:key]] UTF8String]);
  303. }
  304. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  305. }
  306. @end
  307. /******************************************************************************
  308. * Implementation VLCMedia (Private)
  309. */
  310. @implementation VLCMedia (Private)
  311. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  312. {
  313. static NSDictionary * stringToMetaDictionary = nil;
  314. // TODO: Thread safe-ize
  315. if( !stringToMetaDictionary )
  316. {
  317. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  318. stringToMetaDictionary =
  319. [[NSDictionary dictionaryWithObjectsAndKeys:
  320. VLCStringToMeta(Title),
  321. VLCStringToMeta(Artist),
  322. VLCStringToMeta(Genre),
  323. VLCStringToMeta(Copyright),
  324. VLCStringToMeta(Album),
  325. VLCStringToMeta(TrackNumber),
  326. VLCStringToMeta(Description),
  327. VLCStringToMeta(Rating),
  328. VLCStringToMeta(Date),
  329. VLCStringToMeta(Setting),
  330. VLCStringToMeta(URL),
  331. VLCStringToMeta(Language),
  332. VLCStringToMeta(NowPlaying),
  333. VLCStringToMeta(Publisher),
  334. VLCStringToMeta(ArtworkURL),
  335. VLCStringToMeta(TrackID),
  336. nil] retain];
  337. #undef VLCStringToMeta
  338. }
  339. NSNumber * number = [stringToMetaDictionary objectForKey:string];
  340. return number ? [number intValue] : -1;
  341. }
  342. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  343. {
  344. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  345. VLCMetaToString(Title, type);
  346. VLCMetaToString(Artist, type);
  347. VLCMetaToString(Genre, type);
  348. VLCMetaToString(Copyright, type);
  349. VLCMetaToString(Album, type);
  350. VLCMetaToString(TrackNumber, type);
  351. VLCMetaToString(Description, type);
  352. VLCMetaToString(Rating, type);
  353. VLCMetaToString(Date, type);
  354. VLCMetaToString(Setting, type);
  355. VLCMetaToString(URL, type);
  356. VLCMetaToString(Language, type);
  357. VLCMetaToString(NowPlaying, type);
  358. VLCMetaToString(Publisher, type);
  359. VLCMetaToString(ArtworkURL, type);
  360. VLCMetaToString(TrackID, type);
  361. #undef VLCMetaToString
  362. return nil;
  363. }
  364. - (void)initInternalMediaDescriptor
  365. {
  366. char * p_url = libvlc_media_get_mrl( p_md );
  367. url = [[NSURL URLWithString:[NSString stringWithUTF8String:p_url]] retain];
  368. if( !url ) /* Attempt to interpret as a file path then */
  369. url = [[NSURL fileURLWithPath:[NSString stringWithUTF8String:p_url]] retain];
  370. free( p_url );
  371. libvlc_media_set_user_data( p_md, (void*)self );
  372. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md );
  373. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, self);
  374. libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, self);
  375. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, self);
  376. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, self);
  377. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  378. if (!p_mlist)
  379. subitems = nil;
  380. else
  381. {
  382. subitems = [[VLCMediaList mediaListWithLibVLCMediaList:p_mlist] retain];
  383. libvlc_media_list_release( p_mlist );
  384. }
  385. state = LibVLCStateToMediaState(libvlc_media_get_state( p_md ));
  386. }
  387. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  388. {
  389. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType] );
  390. NSString * newValue = psz_value ? [NSString stringWithUTF8String: psz_value] : nil;
  391. NSString * oldValue = [metaDictionary valueForKey:metaType];
  392. free(psz_value);
  393. if ( newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame) )
  394. {
  395. // Only fetch the art if needed. (ie, create the NSImage, if it was requested before)
  396. if (isArtFetched && [metaType isEqualToString:VLCMetaInformationArtworkURL])
  397. {
  398. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  399. toTarget:self
  400. withObject:newValue];
  401. }
  402. [metaDictionary setValue:newValue forKeyPath:metaType];
  403. }
  404. }
  405. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  406. {
  407. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  408. NSImage * art = nil;
  409. if( anURL )
  410. {
  411. // Go ahead and load up the art work
  412. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  413. // Don't attempt to fetch artwork from remote. Core will do that alone
  414. if ([artUrl isFileURL])
  415. art = [[[NSImage alloc] initWithContentsOfURL:artUrl] autorelease];
  416. }
  417. // If anything was found, lets save it to the meta data dictionary
  418. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  419. [pool release];
  420. }
  421. - (void)setArtwork:(NSImage *)art
  422. {
  423. if (!art)
  424. {
  425. [metaDictionary removeObjectForKey:@"artwork"];
  426. return;
  427. }
  428. [metaDictionary setObject:art forKey:@"artwork"];
  429. }
  430. - (void)metaChanged:(NSString *)metaType
  431. {
  432. [self fetchMetaInformationFromLibVLCWithType:metaType];
  433. }
  434. - (void)subItemAdded
  435. {
  436. if( subitems )
  437. return; /* Nothing to do */
  438. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  439. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  440. [self willChangeValueForKey:@"subitems"];
  441. subitems = [[VLCMediaList mediaListWithLibVLCMediaList:p_mlist] retain];
  442. [self didChangeValueForKey:@"subitems"];
  443. libvlc_media_list_release( p_mlist );
  444. }
  445. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  446. {
  447. [self setState: [newStateAsNumber intValue]];
  448. }
  449. - (id)valueForKeyPath:(NSString *)keyPath
  450. {
  451. if( !isArtFetched && [keyPath isEqualToString:@"metaDictionary.artwork"])
  452. {
  453. isArtFetched = YES;
  454. /* Force the retrieval of the artwork now that someone asked for it */
  455. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  456. }
  457. else if( !areOthersMetaFetched && [keyPath hasPrefix:@"metaDictionary."])
  458. {
  459. areOthersMetaFetched = YES;
  460. /* Force VLCMetaInformationTitle, that will trigger preparsing
  461. * And all the other meta will be added through the libvlc event system */
  462. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  463. }
  464. else if( !isArtURLFetched && [keyPath hasPrefix:@"metaDictionary.artworkURL"])
  465. {
  466. isArtURLFetched = YES;
  467. /* Force isArtURLFetched, that will trigger artwork download eventually
  468. * And all the other meta will be added through the libvlc event system */
  469. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  470. }
  471. return [super valueForKeyPath:keyPath];
  472. }
  473. @end
  474. /******************************************************************************
  475. * Implementation VLCMedia (VLCMediaPlayerBridging)
  476. */
  477. @implementation VLCMedia (VLCMediaPlayerBridging)
  478. - (void)setLength:(VLCTime *)value
  479. {
  480. if (length && value && [length compare:value] == NSOrderedSame)
  481. return;
  482. [length release];
  483. length = value ? [value retain] : nil;
  484. }
  485. @end