VLCMedia.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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)setValue:(NSString *)value forMeta:(NSString *)meta
  186. {
  187. libvlc_meta_t metaName = [VLCMedia stringToMetaType:meta];
  188. NSAssert(metaName >= 0, @"Invalid meta");
  189. libvlc_media_set_meta(p_md, metaName, [value UTF8String]);
  190. }
  191. - (void)release
  192. {
  193. @synchronized(self)
  194. {
  195. if([self retainCount] <= 1)
  196. {
  197. /* We must make sure we won't receive new event after an upcoming dealloc
  198. * We also may receive a -retain in some event callback that may occcur
  199. * Before libvlc_event_detach. So this can't happen in dealloc */
  200. libvlc_event_manager_t * p_em = libvlc_media_event_manager(p_md);
  201. libvlc_event_detach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, self);
  202. libvlc_event_detach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, self);
  203. libvlc_event_detach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, self);
  204. libvlc_event_detach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, self);
  205. }
  206. [super release];
  207. }
  208. }
  209. - (void)dealloc
  210. {
  211. // Testing to see if the pointer exists is not required, if the pointer is null
  212. // then the release message is not sent to it.
  213. delegate = nil;
  214. [length release];
  215. [url release];
  216. [subitems release];
  217. [metaDictionary release];
  218. libvlc_media_release( p_md );
  219. [super dealloc];
  220. }
  221. - (NSString *)description
  222. {
  223. NSString * result = [metaDictionary objectForKey:VLCMetaInformationTitle];
  224. return [NSString stringWithFormat:@"<%@ %p> %@", [self className], self, (result ? result : [url absoluteString])];
  225. }
  226. - (NSComparisonResult)compare:(VLCMedia *)media
  227. {
  228. if (self == media)
  229. return NSOrderedSame;
  230. if (!media)
  231. return NSOrderedDescending;
  232. return p_md == [media libVLCMediaDescriptor] ? NSOrderedSame : NSOrderedAscending;
  233. }
  234. @synthesize delegate;
  235. - (VLCTime *)length
  236. {
  237. if (!length)
  238. {
  239. // Try figuring out what the length is
  240. long long duration = libvlc_media_get_duration( p_md );
  241. if (duration > -1)
  242. {
  243. length = [[VLCTime timeWithNumber:[NSNumber numberWithLongLong:duration]] retain];
  244. return [[length retain] autorelease];
  245. }
  246. return [VLCTime nullTime];
  247. }
  248. return [[length retain] autorelease];
  249. }
  250. - (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
  251. {
  252. static const long long thread_sleep = 10000;
  253. if (!length)
  254. {
  255. // Force preparsing of this item.
  256. [self length];
  257. // wait until we are preparsed
  258. while (!length && ![self isParsed] && [aDate timeIntervalSinceNow] > 0)
  259. {
  260. usleep( thread_sleep );
  261. }
  262. // So we're done waiting, but sometimes we trap the fact that the parsing
  263. // was done before the length gets assigned, so lets go ahead and assign
  264. // it ourselves.
  265. if (!length)
  266. return [self length];
  267. }
  268. return [[length retain] autorelease];
  269. }
  270. - (BOOL)isParsed
  271. {
  272. return libvlc_media_is_parsed( p_md );
  273. }
  274. @synthesize url;
  275. @synthesize subitems;
  276. @synthesize metaDictionary;
  277. @synthesize state;
  278. @end
  279. /******************************************************************************
  280. * Implementation VLCMedia (LibVLCBridging)
  281. */
  282. @implementation VLCMedia (LibVLCBridging)
  283. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  284. {
  285. return [[[VLCMedia alloc] initWithLibVLCMediaDescriptor:md] autorelease];
  286. }
  287. - (id)initWithLibVLCMediaDescriptor:(void *)md
  288. {
  289. if (self = [super init])
  290. {
  291. libvlc_media_retain( md );
  292. p_md = md;
  293. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  294. [self initInternalMediaDescriptor];
  295. }
  296. return self;
  297. }
  298. - (void *)libVLCMediaDescriptor
  299. {
  300. return p_md;
  301. }
  302. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  303. {
  304. libvlc_media_t * p_md;
  305. p_md = libvlc_media_duplicate( [media libVLCMediaDescriptor] );
  306. for( NSString * key in [options allKeys] )
  307. {
  308. if ( [options objectForKey:key] != [NSNull null] )
  309. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, [options objectForKey:key]] UTF8String]);
  310. else
  311. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@", key] UTF8String]);
  312. }
  313. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  314. }
  315. @end
  316. /******************************************************************************
  317. * Implementation VLCMedia (Private)
  318. */
  319. @implementation VLCMedia (Private)
  320. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  321. {
  322. static NSDictionary * stringToMetaDictionary = nil;
  323. // TODO: Thread safe-ize
  324. if( !stringToMetaDictionary )
  325. {
  326. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  327. stringToMetaDictionary =
  328. [[NSDictionary dictionaryWithObjectsAndKeys:
  329. VLCStringToMeta(Title),
  330. VLCStringToMeta(Artist),
  331. VLCStringToMeta(Genre),
  332. VLCStringToMeta(Copyright),
  333. VLCStringToMeta(Album),
  334. VLCStringToMeta(TrackNumber),
  335. VLCStringToMeta(Description),
  336. VLCStringToMeta(Rating),
  337. VLCStringToMeta(Date),
  338. VLCStringToMeta(Setting),
  339. VLCStringToMeta(URL),
  340. VLCStringToMeta(Language),
  341. VLCStringToMeta(NowPlaying),
  342. VLCStringToMeta(Publisher),
  343. VLCStringToMeta(ArtworkURL),
  344. VLCStringToMeta(TrackID),
  345. nil] retain];
  346. #undef VLCStringToMeta
  347. }
  348. NSNumber * number = [stringToMetaDictionary objectForKey:string];
  349. return number ? [number intValue] : -1;
  350. }
  351. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  352. {
  353. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  354. VLCMetaToString(Title, type);
  355. VLCMetaToString(Artist, type);
  356. VLCMetaToString(Genre, type);
  357. VLCMetaToString(Copyright, type);
  358. VLCMetaToString(Album, type);
  359. VLCMetaToString(TrackNumber, type);
  360. VLCMetaToString(Description, type);
  361. VLCMetaToString(Rating, type);
  362. VLCMetaToString(Date, type);
  363. VLCMetaToString(Setting, type);
  364. VLCMetaToString(URL, type);
  365. VLCMetaToString(Language, type);
  366. VLCMetaToString(NowPlaying, type);
  367. VLCMetaToString(Publisher, type);
  368. VLCMetaToString(ArtworkURL, type);
  369. VLCMetaToString(TrackID, type);
  370. #undef VLCMetaToString
  371. return nil;
  372. }
  373. - (void)initInternalMediaDescriptor
  374. {
  375. char * p_url = libvlc_media_get_mrl( p_md );
  376. url = [[NSURL URLWithString:[NSString stringWithUTF8String:p_url]] retain];
  377. if( !url ) /* Attempt to interpret as a file path then */
  378. url = [[NSURL fileURLWithPath:[NSString stringWithUTF8String:p_url]] retain];
  379. free( p_url );
  380. libvlc_media_set_user_data( p_md, (void*)self );
  381. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md );
  382. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, self);
  383. libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, self);
  384. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, self);
  385. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, self);
  386. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  387. if (!p_mlist)
  388. subitems = nil;
  389. else
  390. {
  391. subitems = [[VLCMediaList mediaListWithLibVLCMediaList:p_mlist] retain];
  392. libvlc_media_list_release( p_mlist );
  393. }
  394. state = LibVLCStateToMediaState(libvlc_media_get_state( p_md ));
  395. }
  396. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  397. {
  398. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType] );
  399. NSString * newValue = psz_value ? [NSString stringWithUTF8String: psz_value] : nil;
  400. NSString * oldValue = [metaDictionary valueForKey:metaType];
  401. free(psz_value);
  402. if ( newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame) )
  403. {
  404. // Only fetch the art if needed. (ie, create the NSImage, if it was requested before)
  405. if (isArtFetched && [metaType isEqualToString:VLCMetaInformationArtworkURL])
  406. {
  407. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  408. toTarget:self
  409. withObject:newValue];
  410. }
  411. [metaDictionary setValue:newValue forKeyPath:metaType];
  412. }
  413. }
  414. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  415. {
  416. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  417. NSImage * art = nil;
  418. if( anURL )
  419. {
  420. // Go ahead and load up the art work
  421. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  422. // Don't attempt to fetch artwork from remote. Core will do that alone
  423. if ([artUrl isFileURL])
  424. art = [[[NSImage alloc] initWithContentsOfURL:artUrl] autorelease];
  425. }
  426. // If anything was found, lets save it to the meta data dictionary
  427. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  428. [pool release];
  429. }
  430. - (void)setArtwork:(NSImage *)art
  431. {
  432. if (!art)
  433. {
  434. [metaDictionary removeObjectForKey:@"artwork"];
  435. return;
  436. }
  437. [metaDictionary setObject:art forKey:@"artwork"];
  438. }
  439. - (void)metaChanged:(NSString *)metaType
  440. {
  441. [self fetchMetaInformationFromLibVLCWithType:metaType];
  442. }
  443. - (void)subItemAdded
  444. {
  445. if( subitems )
  446. return; /* Nothing to do */
  447. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  448. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  449. [self willChangeValueForKey:@"subitems"];
  450. subitems = [[VLCMediaList mediaListWithLibVLCMediaList:p_mlist] retain];
  451. [self didChangeValueForKey:@"subitems"];
  452. libvlc_media_list_release( p_mlist );
  453. }
  454. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  455. {
  456. [self setState: [newStateAsNumber intValue]];
  457. }
  458. - (id)valueForKeyPath:(NSString *)keyPath
  459. {
  460. if( !isArtFetched && [keyPath isEqualToString:@"metaDictionary.artwork"])
  461. {
  462. isArtFetched = YES;
  463. /* Force the retrieval of the artwork now that someone asked for it */
  464. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  465. }
  466. else if( !areOthersMetaFetched && [keyPath hasPrefix:@"metaDictionary."])
  467. {
  468. areOthersMetaFetched = YES;
  469. /* Force VLCMetaInformationTitle, that will trigger preparsing
  470. * And all the other meta will be added through the libvlc event system */
  471. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  472. }
  473. else if( !isArtURLFetched && [keyPath hasPrefix:@"metaDictionary.artworkURL"])
  474. {
  475. isArtURLFetched = YES;
  476. /* Force isArtURLFetched, that will trigger artwork download eventually
  477. * And all the other meta will be added through the libvlc event system */
  478. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  479. }
  480. return [super valueForKeyPath:keyPath];
  481. }
  482. @end
  483. /******************************************************************************
  484. * Implementation VLCMedia (VLCMediaPlayerBridging)
  485. */
  486. @implementation VLCMedia (VLCMediaPlayerBridging)
  487. - (void)setLength:(VLCTime *)value
  488. {
  489. if (length && value && [length compare:value] == NSOrderedSame)
  490. return;
  491. [length release];
  492. length = value ? [value retain] : nil;
  493. }
  494. @end