VLCMedia.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. //
  113. // [[VLCEventManager sharedManager] callOnMainThreadObject:self
  114. // withMethod:@selector(setLength:)
  115. // withArgumentAsObject:[VLCTime timeWithNumber:
  116. // [NSNumber numberWithLongLong:event->u.media_duration_changed.new_duration]]];
  117. // [pool release];
  118. //}
  119. static void HandleMediaStateChanged(const libvlc_event_t * event, void * self)
  120. {
  121. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  122. [[VLCEventManager sharedManager] callOnMainThreadObject:self
  123. withMethod:@selector(setStateAsNumber:)
  124. withArgumentAsObject:[NSNumber numberWithInt:
  125. LibVLCStateToMediaState(event->u.media_state_changed.new_state)]];
  126. [pool release];
  127. }
  128. static void HandleMediaSubItemAdded(const libvlc_event_t * event, void * self)
  129. {
  130. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  131. [[VLCEventManager sharedManager] callOnMainThreadObject:self
  132. withMethod:@selector(subItemAdded)
  133. withArgumentAsObject:nil];
  134. [pool release];
  135. }
  136. /******************************************************************************
  137. * Implementation
  138. */
  139. @implementation VLCMedia
  140. + (id)mediaWithURL:(NSURL *)anURL;
  141. {
  142. return [[[VLCMedia alloc] initWithURL:anURL] autorelease];
  143. }
  144. + (id)mediaWithPath:(NSString *)aPath;
  145. {
  146. return [[[VLCMedia alloc] initWithPath:aPath] autorelease];
  147. }
  148. + (id)mediaAsNodeWithName:(NSString *)aName;
  149. {
  150. return [[[VLCMedia alloc] initAsNodeWithName:aName] autorelease];
  151. }
  152. - (id)initWithPath:(NSString *)aPath
  153. {
  154. return [self initWithURL:[NSURL fileURLWithPath:aPath isDirectory:NO]];
  155. }
  156. - (id)initWithURL:(NSURL *)anURL
  157. {
  158. if (self = [super init])
  159. {
  160. libvlc_exception_t ex;
  161. libvlc_exception_init(&ex);
  162. p_md = libvlc_media_new([VLCLibrary sharedInstance],
  163. [[anURL absoluteString] UTF8String],
  164. &ex);
  165. catch_exception(&ex);
  166. delegate = nil;
  167. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  168. // This value is set whenever the demuxer figures out what the length is.
  169. // TODO: Easy way to tell the length of the movie without having to instiate the demuxer. Maybe cached info?
  170. length = nil;
  171. [self initInternalMediaDescriptor];
  172. }
  173. return self;
  174. }
  175. - (id)initAsNodeWithName:(NSString *)aName
  176. {
  177. if (self = [super init])
  178. {
  179. libvlc_exception_t ex;
  180. libvlc_exception_init(&ex);
  181. p_md = libvlc_media_new_as_node([VLCLibrary sharedInstance],
  182. [aName UTF8String],
  183. &ex);
  184. catch_exception(&ex);
  185. delegate = nil;
  186. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  187. // This value is set whenever the demuxer figures out what the length is.
  188. // TODO: Easy way to tell the length of the movie without having to instiate the demuxer. Maybe cached info?
  189. length = nil;
  190. [self initInternalMediaDescriptor];
  191. }
  192. return self;
  193. }
  194. - (void)release
  195. {
  196. @synchronized(self)
  197. {
  198. if([self retainCount] <= 1)
  199. {
  200. /* We must make sure we won't receive new event after an upcoming dealloc
  201. * We also may receive a -retain in some event callback that may occcur
  202. * Before libvlc_event_detach. So this can't happen in dealloc */
  203. libvlc_event_manager_t * p_em = libvlc_media_event_manager(p_md);
  204. libvlc_event_detach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, self, NULL);
  205. // libvlc_event_detach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, self, NULL);
  206. libvlc_event_detach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, self, NULL);
  207. libvlc_event_detach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, self, NULL);
  208. }
  209. [super release];
  210. }
  211. }
  212. - (void)dealloc
  213. {
  214. // Testing to see if the pointer exists is not required, if the pointer is null
  215. // then the release message is not sent to it.
  216. delegate = nil;
  217. [self setLength:nil];
  218. [url release];
  219. [subitems release];
  220. [metaDictionary release];
  221. libvlc_media_release( p_md );
  222. [super dealloc];
  223. }
  224. - (NSString *)description
  225. {
  226. NSString * result = [metaDictionary objectForKey:VLCMetaInformationTitle];
  227. return [NSString stringWithFormat:@"<%@ %p> %@", [self className], self, (result ? result : [url absoluteString])];
  228. }
  229. - (NSComparisonResult)compare:(VLCMedia *)media
  230. {
  231. if (self == media)
  232. return NSOrderedSame;
  233. if (!media)
  234. return NSOrderedDescending;
  235. return p_md == [media libVLCMediaDescriptor] ? NSOrderedSame : NSOrderedAscending;
  236. }
  237. @synthesize delegate;
  238. - (VLCTime *)length
  239. {
  240. if (!length)
  241. {
  242. // Try figuring out what the length is
  243. long long duration = libvlc_media_get_duration( p_md, NULL );
  244. if (duration > -1)
  245. {
  246. [self setLength:[VLCTime timeWithNumber:[NSNumber numberWithLongLong:duration]]];
  247. return [[length retain] autorelease];
  248. }
  249. return [VLCTime nullTime];
  250. }
  251. return [[length retain] autorelease];
  252. }
  253. - (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
  254. {
  255. static const long long thread_sleep = 10000;
  256. if (!length)
  257. {
  258. while (!length && ![self isPreparsed] && [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)isPreparsed
  271. {
  272. return libvlc_media_is_preparsed( 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. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=#%@", key, [options objectForKey:key]] UTF8String]);
  309. }
  310. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  311. }
  312. @end
  313. /******************************************************************************
  314. * Implementation VLCMedia (Private)
  315. */
  316. @implementation VLCMedia (Private)
  317. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  318. {
  319. static NSDictionary * stringToMetaDictionary = nil;
  320. // TODO: Thread safe-ize
  321. if( !stringToMetaDictionary )
  322. {
  323. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  324. stringToMetaDictionary =
  325. [[NSDictionary dictionaryWithObjectsAndKeys:
  326. VLCStringToMeta(Title),
  327. VLCStringToMeta(Artist),
  328. VLCStringToMeta(Genre),
  329. VLCStringToMeta(Copyright),
  330. VLCStringToMeta(Album),
  331. VLCStringToMeta(TrackNumber),
  332. VLCStringToMeta(Description),
  333. VLCStringToMeta(Rating),
  334. VLCStringToMeta(Date),
  335. VLCStringToMeta(Setting),
  336. VLCStringToMeta(URL),
  337. VLCStringToMeta(Language),
  338. VLCStringToMeta(NowPlaying),
  339. VLCStringToMeta(Publisher),
  340. VLCStringToMeta(ArtworkURL),
  341. VLCStringToMeta(TrackID),
  342. nil] retain];
  343. #undef VLCStringToMeta
  344. }
  345. NSNumber * number = [stringToMetaDictionary objectForKey:string];
  346. return number ? [number intValue] : -1;
  347. }
  348. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  349. {
  350. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  351. VLCMetaToString(Title, type);
  352. VLCMetaToString(Artist, type);
  353. VLCMetaToString(Genre, type);
  354. VLCMetaToString(Copyright, type);
  355. VLCMetaToString(Album, type);
  356. VLCMetaToString(TrackNumber, type);
  357. VLCMetaToString(Description, type);
  358. VLCMetaToString(Rating, type);
  359. VLCMetaToString(Date, type);
  360. VLCMetaToString(Setting, type);
  361. VLCMetaToString(URL, type);
  362. VLCMetaToString(Language, type);
  363. VLCMetaToString(NowPlaying, type);
  364. VLCMetaToString(Publisher, type);
  365. VLCMetaToString(ArtworkURL, type);
  366. VLCMetaToString(TrackID, type);
  367. #undef VLCMetaToString
  368. return nil;
  369. }
  370. - (void)initInternalMediaDescriptor
  371. {
  372. libvlc_exception_t ex;
  373. libvlc_exception_init( &ex );
  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, &ex);
  382. // libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, self, &ex);
  383. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, self, &ex);
  384. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, self, &ex);
  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. if ([metaType isEqualToString:VLCMetaInformationArtworkURL])
  404. {
  405. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  406. toTarget:self
  407. withObject:newValue];
  408. return;
  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. return [super valueForKeyPath:keyPath];
  473. }
  474. @end
  475. /******************************************************************************
  476. * Implementation VLCMedia (VLCMediaPlayerBridging)
  477. */
  478. @implementation VLCMedia (VLCMediaPlayerBridging)
  479. - (void)setLength:(VLCTime *)value
  480. {
  481. if (length && value && [length compare:value] == NSOrderedSame)
  482. return;
  483. [length release];
  484. length = value ? [value retain] : nil;
  485. }
  486. @end