VLCMedia.m 19 KB

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