VLCMedia.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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, NULL);
  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. }
  250. return [VLCTime nullTime];
  251. }
  252. - (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
  253. {
  254. static const long long thread_sleep = 10000;
  255. if (!length)
  256. {
  257. while (!length && ![self isPreparsed] && [aDate timeIntervalSinceNow] > 0)
  258. {
  259. usleep( thread_sleep );
  260. }
  261. // So we're done waiting, but sometimes we trap the fact that the parsing
  262. // was done before the length gets assigned, so lets go ahead and assign
  263. // it ourselves.
  264. if (!length)
  265. return [self length];
  266. }
  267. return [[length retain] autorelease];
  268. }
  269. - (BOOL)isPreparsed
  270. {
  271. return libvlc_media_is_preparsed( p_md, NULL );
  272. }
  273. @synthesize url;
  274. @synthesize subitems;
  275. @synthesize metaDictionary;
  276. @synthesize state;
  277. @end
  278. /******************************************************************************
  279. * Implementation VLCMedia (LibVLCBridging)
  280. */
  281. @implementation VLCMedia (LibVLCBridging)
  282. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  283. {
  284. return [[[VLCMedia alloc] initWithLibVLCMediaDescriptor:md] autorelease];
  285. }
  286. - (id)initWithLibVLCMediaDescriptor:(void *)md
  287. {
  288. if (self = [super init])
  289. {
  290. libvlc_exception_t ex;
  291. libvlc_exception_init( &ex );
  292. libvlc_media_retain( md );
  293. p_md = md;
  294. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  295. [self initInternalMediaDescriptor];
  296. }
  297. return self;
  298. }
  299. - (void *)libVLCMediaDescriptor
  300. {
  301. return p_md;
  302. }
  303. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  304. {
  305. libvlc_media_t * p_md;
  306. p_md = libvlc_media_duplicate( [media libVLCMediaDescriptor] );
  307. for( NSString * key in [options allKeys] )
  308. {
  309. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=#%@", key, [options objectForKey:key]] UTF8String], NULL);
  310. }
  311. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  312. }
  313. @end
  314. /******************************************************************************
  315. * Implementation VLCMedia (Private)
  316. */
  317. @implementation VLCMedia (Private)
  318. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  319. {
  320. static NSDictionary * stringToMetaDictionary = nil;
  321. // TODO: Thread safe-ize
  322. if( !stringToMetaDictionary )
  323. {
  324. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  325. stringToMetaDictionary =
  326. [[NSDictionary dictionaryWithObjectsAndKeys:
  327. VLCStringToMeta(Title),
  328. VLCStringToMeta(Artist),
  329. VLCStringToMeta(Genre),
  330. VLCStringToMeta(Copyright),
  331. VLCStringToMeta(Album),
  332. VLCStringToMeta(TrackNumber),
  333. VLCStringToMeta(Description),
  334. VLCStringToMeta(Rating),
  335. VLCStringToMeta(Date),
  336. VLCStringToMeta(Setting),
  337. VLCStringToMeta(URL),
  338. VLCStringToMeta(Language),
  339. VLCStringToMeta(NowPlaying),
  340. VLCStringToMeta(Publisher),
  341. VLCStringToMeta(ArtworkURL),
  342. VLCStringToMeta(TrackID),
  343. nil] retain];
  344. #undef VLCStringToMeta
  345. }
  346. NSNumber * number = [stringToMetaDictionary objectForKey:string];
  347. return number ? [number intValue] : -1;
  348. }
  349. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  350. {
  351. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  352. VLCMetaToString(Title, type);
  353. VLCMetaToString(Artist, type);
  354. VLCMetaToString(Genre, type);
  355. VLCMetaToString(Copyright, type);
  356. VLCMetaToString(Album, type);
  357. VLCMetaToString(TrackNumber, type);
  358. VLCMetaToString(Description, type);
  359. VLCMetaToString(Rating, type);
  360. VLCMetaToString(Date, type);
  361. VLCMetaToString(Setting, type);
  362. VLCMetaToString(URL, type);
  363. VLCMetaToString(Language, type);
  364. VLCMetaToString(NowPlaying, type);
  365. VLCMetaToString(Publisher, type);
  366. VLCMetaToString(ArtworkURL, type);
  367. VLCMetaToString(TrackID, type);
  368. #undef VLCMetaToString
  369. return nil;
  370. }
  371. - (void)initInternalMediaDescriptor
  372. {
  373. libvlc_exception_t ex;
  374. libvlc_exception_init( &ex );
  375. artFetched = NO;
  376. char * p_url = libvlc_media_get_mrl( p_md, &ex );
  377. catch_exception( &ex );
  378. url = [[NSURL URLWithString:[NSString stringWithUTF8String:p_url]] retain];
  379. if( !url ) /* Attempt to interpret as a file path then */
  380. url = [[NSURL fileURLWithPath:[NSString stringWithUTF8String:p_url]] retain];
  381. free( p_url );
  382. libvlc_media_set_user_data( p_md, (void*)self, &ex );
  383. catch_exception( &ex );
  384. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md, &ex );
  385. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, self, &ex);
  386. // libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, self, &ex);
  387. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, self, &ex);
  388. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, self, &ex);
  389. catch_exception( &ex );
  390. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md, NULL );
  391. if (!p_mlist)
  392. subitems = nil;
  393. else
  394. {
  395. subitems = [[VLCMediaList mediaListWithLibVLCMediaList:p_mlist] retain];
  396. libvlc_media_list_release( p_mlist );
  397. }
  398. state = LibVLCStateToMediaState(libvlc_media_get_state( p_md, NULL ));
  399. /* Force VLCMetaInformationTitle, that will trigger preparsing
  400. * And all the other meta will be added through the libvlc event system */
  401. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  402. }
  403. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  404. {
  405. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType], NULL);
  406. NSString * newValue = psz_value ? [NSString stringWithUTF8String: psz_value] : nil;
  407. NSString * oldValue = [metaDictionary valueForKey:metaType];
  408. free(psz_value);
  409. if ( newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame) )
  410. {
  411. if ([metaType isEqualToString:VLCMetaInformationArtworkURL])
  412. {
  413. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  414. toTarget:self
  415. withObject:newValue];
  416. return;
  417. }
  418. [metaDictionary setValue:newValue forKeyPath:metaType];
  419. }
  420. }
  421. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  422. {
  423. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  424. NSImage * art = nil;
  425. if( anURL )
  426. {
  427. // Go ahead and load up the art work
  428. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  429. // Don't attempt to fetch artwork from remote. Core will do that alone
  430. if ([artUrl isFileURL])
  431. art = [[[NSImage alloc] initWithContentsOfURL:artUrl] autorelease];
  432. }
  433. // If anything was found, lets save it to the meta data dictionary
  434. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  435. [pool release];
  436. }
  437. - (void)setArtwork:(NSImage *)art
  438. {
  439. if (!art)
  440. {
  441. [metaDictionary removeObjectForKey:@"artwork"];
  442. return;
  443. }
  444. [metaDictionary setObject:art forKey:@"artwork"];
  445. }
  446. - (void)metaChanged:(NSString *)metaType
  447. {
  448. [self fetchMetaInformationFromLibVLCWithType:metaType];
  449. }
  450. - (void)subItemAdded
  451. {
  452. if( subitems )
  453. return; /* Nothing to do */
  454. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md, NULL );
  455. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  456. [self willChangeValueForKey:@"subitems"];
  457. subitems = [[VLCMediaList mediaListWithLibVLCMediaList:p_mlist] retain];
  458. [self didChangeValueForKey:@"subitems"];
  459. libvlc_media_list_release( p_mlist );
  460. }
  461. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  462. {
  463. [self setState: [newStateAsNumber intValue]];
  464. }
  465. - (id)valueForKeyPath:(NSString *)keyPath
  466. {
  467. if( !artFetched && [keyPath isEqualToString:@"metaDictionary.artwork"])
  468. {
  469. artFetched = YES;
  470. /* Force the retrieval of the artwork now that someone asked for it */
  471. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  472. }
  473. return [super valueForKeyPath:keyPath];
  474. }
  475. @end
  476. /******************************************************************************
  477. * Implementation VLCMedia (VLCMediaPlayerBridging)
  478. */
  479. @implementation VLCMedia (VLCMediaPlayerBridging)
  480. - (void)setLength:(VLCTime *)value
  481. {
  482. if (length && value && [length compare:value] == NSOrderedSame)
  483. return;
  484. [length release];
  485. length = value ? [value retain] : nil;
  486. }
  487. @end