VLCMedia.m 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. /*****************************************************************************
  2. * VLCMedia.m: VLCKit.framework VLCMedia implementation
  3. *****************************************************************************
  4. * Copyright (C) 2007 Pierre d'Herbemont
  5. * Copyright (C) 2013 Felix Paul Kühne
  6. * Copyright (C) 2007, 2013 VLC authors and VideoLAN
  7. * $Id$
  8. *
  9. * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
  10. * Felix Paul Kühne <fkuehne # videolan.org>
  11. *
  12. * This program is free software; you can redistribute it and/or modify it
  13. * under the terms of the GNU Lesser General Public License as published by
  14. * the Free Software Foundation; either version 2.1 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public License
  23. * along with this program; if not, write to the Free Software Foundation,
  24. * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  25. *****************************************************************************/
  26. #import "VLCMedia.h"
  27. #import "VLCMediaList.h"
  28. #import "VLCEventManager.h"
  29. #import "VLCLibrary.h"
  30. #import "VLCLibVLCBridging.h"
  31. #import <vlc/libvlc.h>
  32. #import <sys/sysctl.h> // for sysctlbyname
  33. /* Meta Dictionary Keys */
  34. NSString *const VLCMetaInformationTitle = @"title";
  35. NSString *const VLCMetaInformationArtist = @"artist";
  36. NSString *const VLCMetaInformationGenre = @"genre";
  37. NSString *const VLCMetaInformationCopyright = @"copyright";
  38. NSString *const VLCMetaInformationAlbum = @"album";
  39. NSString *const VLCMetaInformationTrackNumber = @"trackNumber";
  40. NSString *const VLCMetaInformationDescription = @"description";
  41. NSString *const VLCMetaInformationRating = @"rating";
  42. NSString *const VLCMetaInformationDate = @"date";
  43. NSString *const VLCMetaInformationSetting = @"setting";
  44. NSString *const VLCMetaInformationURL = @"url";
  45. NSString *const VLCMetaInformationLanguage = @"language";
  46. NSString *const VLCMetaInformationNowPlaying = @"nowPlaying";
  47. NSString *const VLCMetaInformationPublisher = @"publisher";
  48. NSString *const VLCMetaInformationEncodedBy = @"encodedBy";
  49. NSString *const VLCMetaInformationArtworkURL = @"artworkURL";
  50. NSString *const VLCMetaInformationArtwork = @"artwork";
  51. NSString *const VLCMetaInformationTrackID = @"trackID";
  52. NSString *const VLCMetaInformationTrackTotal = @"trackTotal";
  53. NSString *const VLCMetaInformationDirector = @"director";
  54. NSString *const VLCMetaInformationSeason = @"season";
  55. NSString *const VLCMetaInformationEpisode = @"episode";
  56. NSString *const VLCMetaInformationShowName = @"showName";
  57. NSString *const VLCMetaInformationActors = @"actors";
  58. NSString *const VLCMetaInformationAlbumArtist = @"AlbumArtist";
  59. NSString *const VLCMetaInformationDiscNumber = @"discNumber";
  60. /* Notification Messages */
  61. NSString *const VLCMediaMetaChanged = @"VLCMediaMetaChanged";
  62. /******************************************************************************
  63. * VLCMedia ()
  64. */
  65. @interface VLCMedia()
  66. {
  67. void * p_md; //< Internal media descriptor instance
  68. BOOL isArtFetched; //< Value used to determine of the artwork has been parsed
  69. BOOL areOthersMetaFetched; //< Value used to determine of the other meta has been parsed
  70. BOOL isArtURLFetched; //< Value used to determine of the other meta has been preparsed
  71. BOOL isParsed;
  72. NSMutableDictionary *_metaDictionary;
  73. }
  74. /* Make our properties internally readwrite */
  75. @property (nonatomic, readwrite) VLCMediaState state;
  76. @property (nonatomic, readwrite, strong) VLCMediaList * subitems;
  77. /* Statics */
  78. + (libvlc_meta_t)stringToMetaType:(NSString *)string;
  79. + (NSString *)metaTypeToString:(libvlc_meta_t)type;
  80. /* Initializers */
  81. - (void)initInternalMediaDescriptor;
  82. /* Operations */
  83. - (void)fetchMetaInformationFromLibVLCWithType:(NSString*)metaType;
  84. #if !TARGET_OS_IPHONE
  85. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL;
  86. - (void)setArtwork:(NSImage *)art;
  87. #endif
  88. - (void)parseIfNeeded;
  89. /* Callback Methods */
  90. - (void)parsedChanged:(NSNumber *)isParsedAsNumber;
  91. - (void)metaChanged:(NSString *)metaType;
  92. - (void)subItemAdded;
  93. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber;
  94. @end
  95. static VLCMediaState libvlc_state_to_media_state[] =
  96. {
  97. [libvlc_NothingSpecial] = VLCMediaStateNothingSpecial,
  98. [libvlc_Stopped] = VLCMediaStateNothingSpecial,
  99. [libvlc_Opening] = VLCMediaStateNothingSpecial,
  100. [libvlc_Buffering] = VLCMediaStateBuffering,
  101. [libvlc_Ended] = VLCMediaStateNothingSpecial,
  102. [libvlc_Error] = VLCMediaStateError,
  103. [libvlc_Playing] = VLCMediaStatePlaying,
  104. [libvlc_Paused] = VLCMediaStatePlaying,
  105. };
  106. static inline VLCMediaState LibVLCStateToMediaState( libvlc_state_t state )
  107. {
  108. return libvlc_state_to_media_state[state];
  109. }
  110. /******************************************************************************
  111. * LibVLC Event Callback
  112. */
  113. static void HandleMediaMetaChanged(const libvlc_event_t * event, void * self)
  114. {
  115. @autoreleasepool {
  116. [[VLCEventManager sharedManager] callOnMainThreadObject:(__bridge id)(self)
  117. withMethod:@selector(metaChanged:)
  118. withArgumentAsObject:[VLCMedia metaTypeToString:event->u.media_meta_changed.meta_type]];
  119. }
  120. }
  121. static void HandleMediaDurationChanged(const libvlc_event_t * event, void * self)
  122. {
  123. @autoreleasepool {
  124. [[VLCEventManager sharedManager] callOnMainThreadObject:(__bridge id)(self)
  125. withMethod:@selector(setLength:)
  126. withArgumentAsObject:[VLCTime timeWithNumber:
  127. @(event->u.media_duration_changed.new_duration)]];
  128. }
  129. }
  130. static void HandleMediaStateChanged(const libvlc_event_t * event, void * self)
  131. {
  132. @autoreleasepool {
  133. [[VLCEventManager sharedManager] callOnMainThreadObject:(__bridge id)(self)
  134. withMethod:@selector(setStateAsNumber:)
  135. withArgumentAsObject:@(LibVLCStateToMediaState(event->u.media_state_changed.new_state))];
  136. }
  137. }
  138. static void HandleMediaSubItemAdded(const libvlc_event_t * event, void * self)
  139. {
  140. @autoreleasepool {
  141. [[VLCEventManager sharedManager] callOnMainThreadObject:(__bridge id)(self)
  142. withMethod:@selector(subItemAdded)
  143. withArgumentAsObject:nil];
  144. }
  145. }
  146. static void HandleMediaParsedChanged(const libvlc_event_t * event, void * self)
  147. {
  148. @autoreleasepool {
  149. [[VLCEventManager sharedManager] callOnMainThreadObject:(__bridge id)(self)
  150. withMethod:@selector(parsedChanged:)
  151. withArgumentAsObject:@((BOOL)event->u.media_parsed_changed.new_status)];
  152. }
  153. }
  154. /******************************************************************************
  155. * Implementation
  156. */
  157. @implementation VLCMedia
  158. + (NSString *)codecNameForFourCC:(uint32_t)fourcc trackType:(NSString *)trackType
  159. {
  160. libvlc_track_type_t track_type = libvlc_track_unknown;
  161. if ([trackType isEqualToString:VLCMediaTracksInformationTypeAudio])
  162. track_type = libvlc_track_audio;
  163. else if ([trackType isEqualToString:VLCMediaTracksInformationTypeVideo])
  164. track_type = libvlc_track_video;
  165. else if ([trackType isEqualToString:VLCMediaTracksInformationTypeText])
  166. track_type = libvlc_track_text;
  167. const char *ret = libvlc_media_get_codec_description(track_type, fourcc);
  168. if (ret)
  169. return [NSString stringWithUTF8String:ret];
  170. return @"";
  171. }
  172. + (instancetype)mediaWithURL:(NSURL *)anURL;
  173. {
  174. return [[VLCMedia alloc] initWithURL:anURL];
  175. }
  176. + (instancetype)mediaWithPath:(NSString *)aPath;
  177. {
  178. return [[VLCMedia alloc] initWithPath:aPath];
  179. }
  180. + (instancetype)mediaAsNodeWithName:(NSString *)aName;
  181. {
  182. return [[VLCMedia alloc] initAsNodeWithName:aName];
  183. }
  184. - (instancetype)initWithPath:(NSString *)aPath
  185. {
  186. return [self initWithURL:[NSURL fileURLWithPath:aPath isDirectory:NO]];
  187. }
  188. - (instancetype)initWithURL:(NSURL *)anURL
  189. {
  190. if (self = [super init]) {
  191. VLCLibrary *library = [VLCLibrary sharedLibrary];
  192. NSAssert(library.instance, @"no library instance when creating media");
  193. p_md = libvlc_media_new_location(library.instance, [[anURL absoluteString] UTF8String]);
  194. _metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  195. [self initInternalMediaDescriptor];
  196. }
  197. return self;
  198. }
  199. - (instancetype)initAsNodeWithName:(NSString *)aName
  200. {
  201. if (self = [super init]) {
  202. p_md = libvlc_media_new_as_node([VLCLibrary sharedInstance], [aName UTF8String]);
  203. _metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  204. [self initInternalMediaDescriptor];
  205. }
  206. return self;
  207. }
  208. - (void)dealloc
  209. {
  210. libvlc_event_manager_t * p_em = libvlc_media_event_manager(p_md);
  211. if (p_em) {
  212. libvlc_event_detach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, (__bridge void *)(self));
  213. libvlc_event_detach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, (__bridge void *)(self));
  214. libvlc_event_detach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, (__bridge void *)(self));
  215. libvlc_event_detach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, (__bridge void *)(self));
  216. libvlc_event_detach(p_em, libvlc_MediaParsedChanged, HandleMediaParsedChanged, (__bridge void *)(self));
  217. }
  218. [[VLCEventManager sharedManager] cancelCallToObject:self];
  219. libvlc_media_release( p_md );
  220. }
  221. - (VLCMediaType)mediaType
  222. {
  223. libvlc_media_type_t libmediatype = libvlc_media_get_type(p_md);
  224. switch (libmediatype) {
  225. case libvlc_media_type_file:
  226. return VLCMediaTypeFile;
  227. case libvlc_media_type_directory:
  228. return VLCMediaTypeDirectory;
  229. case libvlc_media_type_disc:
  230. return VLCMediaTypeDisc;
  231. case libvlc_media_type_stream:
  232. return VLCMediaTypeStream;
  233. case libvlc_media_type_playlist:
  234. return VLCMediaTypePlaylist;
  235. default:
  236. return VLCMediaTypeUnknown;
  237. }
  238. }
  239. - (NSString *)description
  240. {
  241. NSString * result = _metaDictionary[VLCMetaInformationTitle];
  242. return [NSString stringWithFormat:@"<%@ %p> %@", [self class], self, (result ? result : [_url absoluteString])];
  243. }
  244. - (NSComparisonResult)compare:(VLCMedia *)media
  245. {
  246. if (self == media)
  247. return NSOrderedSame;
  248. if (!media)
  249. return NSOrderedDescending;
  250. return p_md == [media libVLCMediaDescriptor] ? NSOrderedSame : NSOrderedAscending;
  251. }
  252. - (VLCTime *)length
  253. {
  254. if (!_length) {
  255. // Try figuring out what the length is
  256. long long duration = libvlc_media_get_duration( p_md );
  257. if (duration < 0)
  258. return [VLCTime nullTime];
  259. _length = [VLCTime timeWithNumber:@(duration)];
  260. }
  261. return _length;
  262. }
  263. - (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
  264. {
  265. static const long long thread_sleep = 10000;
  266. if (!_length) {
  267. // Force parsing of this item.
  268. [self parseIfNeeded];
  269. // wait until we are preparsed
  270. while (!_length && !libvlc_media_is_parsed(p_md) && [aDate timeIntervalSinceNow] > 0)
  271. usleep( thread_sleep );
  272. // So we're done waiting, but sometimes we trap the fact that the parsing
  273. // was done before the length gets assigned, so lets go ahead and assign
  274. // it ourselves.
  275. if (!_length)
  276. return [self length];
  277. }
  278. return _length;
  279. }
  280. - (BOOL)isParsed
  281. {
  282. return isParsed;
  283. }
  284. - (void)parse
  285. {
  286. if (p_md)
  287. libvlc_media_parse_async(p_md);
  288. }
  289. - (void)synchronousParse
  290. {
  291. if (p_md)
  292. libvlc_media_parse(p_md);
  293. }
  294. - (void)addOptions:(NSDictionary*)options
  295. {
  296. if (p_md) {
  297. [options enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
  298. if (![obj isKindOfClass:[NSNull class]])
  299. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, obj] UTF8String]);
  300. else
  301. libvlc_media_add_option(p_md, [key UTF8String]);
  302. }];
  303. }
  304. }
  305. - (NSDictionary*) stats
  306. {
  307. if (!p_md)
  308. return nil;
  309. libvlc_media_stats_t p_stats;
  310. libvlc_media_get_stats(p_md, &p_stats);
  311. return @{
  312. @"demuxBitrate" : @(p_stats.f_demux_bitrate),
  313. @"inputBitrate" : @(p_stats.f_input_bitrate),
  314. @"sendBitrate" : @(p_stats.f_send_bitrate),
  315. @"decodedAudio" : @(p_stats.i_decoded_audio),
  316. @"decodedVideo" : @(p_stats.i_decoded_video),
  317. @"demuxCorrupted" : @(p_stats.i_demux_corrupted),
  318. @"demuxDiscontinuity" : @(p_stats.i_demux_discontinuity),
  319. @"demuxReadBytes" : @(p_stats.i_demux_read_bytes),
  320. @"displayedPictures" : @(p_stats.i_displayed_pictures),
  321. @"lostAbuffers" : @(p_stats.i_lost_abuffers),
  322. @"lostPictures" : @(p_stats.i_lost_pictures),
  323. @"playedAbuffers" : @(p_stats.i_played_abuffers),
  324. @"readBytes" : @(p_stats.i_read_bytes),
  325. @"sentBytes" : @(p_stats.i_sent_bytes),
  326. @"sentPackets" : @(p_stats.i_sent_packets)
  327. };
  328. }
  329. - (NSInteger)numberOfReadBytesOnInput
  330. {
  331. if (!p_md)
  332. return 0;
  333. libvlc_media_stats_t p_stats;
  334. libvlc_media_get_stats(p_md, &p_stats);
  335. return p_stats.i_read_bytes;
  336. }
  337. - (float)inputBitrate
  338. {
  339. if (!p_md)
  340. return .0;
  341. libvlc_media_stats_t p_stats;
  342. libvlc_media_get_stats(p_md, &p_stats);
  343. return p_stats.f_input_bitrate;
  344. }
  345. - (NSInteger)numberOfReadBytesOnDemux
  346. {
  347. if (!p_md)
  348. return 0;
  349. libvlc_media_stats_t p_stats;
  350. libvlc_media_get_stats(p_md, &p_stats);
  351. return p_stats.i_demux_read_bytes;
  352. }
  353. - (float)demuxBitrate
  354. {
  355. if (!p_md)
  356. return .0;
  357. libvlc_media_stats_t p_stats;
  358. libvlc_media_get_stats(p_md, &p_stats);
  359. return p_stats.f_demux_bitrate;
  360. }
  361. - (NSInteger)numberOfDecodedVideoBlocks
  362. {
  363. if (!p_md)
  364. return 0;
  365. libvlc_media_stats_t p_stats;
  366. libvlc_media_get_stats(p_md, &p_stats);
  367. return p_stats.i_decoded_video;
  368. }
  369. - (NSInteger)numberOfDecodedAudioBlocks
  370. {
  371. if (!p_md)
  372. return 0;
  373. libvlc_media_stats_t p_stats;
  374. libvlc_media_get_stats(p_md, &p_stats);
  375. return p_stats.i_decoded_audio;
  376. }
  377. - (NSInteger)numberOfDisplayedPictures
  378. {
  379. if (!p_md)
  380. return 0;
  381. libvlc_media_stats_t p_stats;
  382. libvlc_media_get_stats(p_md, &p_stats);
  383. return p_stats.i_displayed_pictures;
  384. }
  385. - (NSInteger)numberOfLostPictures
  386. {
  387. if (!p_md)
  388. return 0;
  389. libvlc_media_stats_t p_stats;
  390. libvlc_media_get_stats(p_md, &p_stats);
  391. return p_stats.i_lost_pictures;
  392. }
  393. - (NSInteger)numberOfPlayedAudioBuffers
  394. {
  395. if (!p_md)
  396. return 0;
  397. libvlc_media_stats_t p_stats;
  398. libvlc_media_get_stats(p_md, &p_stats);
  399. return p_stats.i_played_abuffers;
  400. }
  401. - (NSInteger)numberOfLostAudioBuffers
  402. {
  403. if (!p_md)
  404. return 0;
  405. libvlc_media_stats_t p_stats;
  406. libvlc_media_get_stats(p_md, &p_stats);
  407. return p_stats.i_lost_abuffers;
  408. }
  409. - (NSInteger)numberOfSentPackets
  410. {
  411. if (!p_md)
  412. return 0;
  413. libvlc_media_stats_t p_stats;
  414. libvlc_media_get_stats(p_md, &p_stats);
  415. return p_stats.i_sent_packets;
  416. }
  417. - (NSInteger)numberOfSentBytes
  418. {
  419. if (!p_md)
  420. return 0;
  421. libvlc_media_stats_t p_stats;
  422. libvlc_media_get_stats(p_md, &p_stats);
  423. return p_stats.i_sent_bytes;
  424. }
  425. - (float)streamOutputBitrate
  426. {
  427. if (!p_md)
  428. return .0;
  429. libvlc_media_stats_t p_stats;
  430. libvlc_media_get_stats(p_md, &p_stats);
  431. return p_stats.f_send_bitrate;
  432. }
  433. - (NSInteger)numberOfCorruptedDataPackets
  434. {
  435. if (!p_md)
  436. return 0;
  437. libvlc_media_stats_t p_stats;
  438. libvlc_media_get_stats(p_md, &p_stats);
  439. return p_stats.i_demux_corrupted;
  440. }
  441. - (NSInteger)numberOfDiscontinuties
  442. {
  443. if (!p_md)
  444. return 0;
  445. libvlc_media_stats_t p_stats;
  446. libvlc_media_get_stats(p_md, &p_stats);
  447. return p_stats.i_demux_discontinuity;
  448. }
  449. NSString *const VLCMediaTracksInformationCodec = @"codec"; // NSNumber
  450. NSString *const VLCMediaTracksInformationId = @"id"; // NSNumber
  451. NSString *const VLCMediaTracksInformationType = @"type"; // NSString
  452. NSString *const VLCMediaTracksInformationCodecProfile = @"profile"; // NSNumber
  453. NSString *const VLCMediaTracksInformationCodecLevel = @"level"; // NSNumber
  454. NSString *const VLCMediaTracksInformationTypeAudio = @"audio";
  455. NSString *const VLCMediaTracksInformationTypeVideo = @"video";
  456. NSString *const VLCMediaTracksInformationTypeText = @"text";
  457. NSString *const VLCMediaTracksInformationTypeUnknown = @"unknown";
  458. NSString *const VLCMediaTracksInformationBitrate = @"bitrate"; // NSNumber
  459. NSString *const VLCMediaTracksInformationLanguage = @"language"; // NSString
  460. NSString *const VLCMediaTracksInformationDescription = @"description"; // NSString
  461. NSString *const VLCMediaTracksInformationAudioChannelsNumber = @"channelsNumber"; // NSNumber
  462. NSString *const VLCMediaTracksInformationAudioRate = @"rate"; // NSNumber
  463. NSString *const VLCMediaTracksInformationVideoHeight = @"height"; // NSNumber
  464. NSString *const VLCMediaTracksInformationVideoWidth = @"width"; // NSNumber
  465. NSString *const VLCMediaTracksInformationSourceAspectRatio = @"sar_num"; // NSNumber
  466. NSString *const VLCMediaTracksInformationSourceAspectDenominator = @"sar_den"; // NSNumber
  467. NSString *const VLCMediaTracksInformationFrameRate = @"frame_rate_num"; // NSNumber
  468. NSString *const VLCMediaTracksInformationFrameRateDenominator = @"frame_rate_den"; // NSNumber
  469. NSString *const VLCMediaTracksInformationTextEncoding = @"encoding"; // NSString
  470. - (NSArray *)tracksInformation
  471. {
  472. [self synchronousParse];
  473. libvlc_media_track_t **tracksInfo;
  474. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  475. NSMutableArray *array = [NSMutableArray array];
  476. for (NSUInteger i = 0; i < count; i++) {
  477. NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  478. @(tracksInfo[i]->i_codec),
  479. VLCMediaTracksInformationCodec,
  480. @(tracksInfo[i]->i_id),
  481. VLCMediaTracksInformationId,
  482. @(tracksInfo[i]->i_profile),
  483. VLCMediaTracksInformationCodecProfile,
  484. @(tracksInfo[i]->i_level),
  485. VLCMediaTracksInformationCodecLevel,
  486. @(tracksInfo[i]->i_bitrate),
  487. VLCMediaTracksInformationBitrate,
  488. nil];
  489. if (tracksInfo[i]->psz_language)
  490. dictionary[VLCMediaTracksInformationLanguage] = [NSString stringWithUTF8String:tracksInfo[i]->psz_language];
  491. if (tracksInfo[i]->psz_description)
  492. dictionary[VLCMediaTracksInformationDescription] = [NSString stringWithUTF8String:tracksInfo[i]->psz_description];
  493. NSString *type;
  494. switch (tracksInfo[i]->i_type) {
  495. case libvlc_track_audio:
  496. type = VLCMediaTracksInformationTypeAudio;
  497. dictionary[VLCMediaTracksInformationAudioChannelsNumber] = @(tracksInfo[i]->audio->i_channels);
  498. dictionary[VLCMediaTracksInformationAudioRate] = @(tracksInfo[i]->audio->i_rate);
  499. break;
  500. case libvlc_track_video:
  501. type = VLCMediaTracksInformationTypeVideo;
  502. dictionary[VLCMediaTracksInformationVideoWidth] = @(tracksInfo[i]->video->i_width);
  503. dictionary[VLCMediaTracksInformationVideoHeight] = @(tracksInfo[i]->video->i_height);
  504. dictionary[VLCMediaTracksInformationSourceAspectRatio] = @(tracksInfo[i]->video->i_sar_num);
  505. dictionary[VLCMediaTracksInformationSourceAspectDenominator] = @(tracksInfo[i]->video->i_sar_den);
  506. dictionary[VLCMediaTracksInformationFrameRate] = @(tracksInfo[i]->video->i_frame_rate_num);
  507. dictionary[VLCMediaTracksInformationFrameRateDenominator] = @(tracksInfo[i]->video->i_frame_rate_den);
  508. break;
  509. case libvlc_track_text:
  510. type = VLCMediaTracksInformationTypeText;
  511. if (tracksInfo[i]->subtitle->psz_encoding)
  512. dictionary[VLCMediaTracksInformationTextEncoding] = [NSString stringWithUTF8String: tracksInfo[i]->subtitle->psz_encoding];
  513. break;
  514. case libvlc_track_unknown:
  515. default:
  516. type = VLCMediaTracksInformationTypeUnknown;
  517. break;
  518. }
  519. [dictionary setValue:type forKey:VLCMediaTracksInformationType];
  520. [array addObject:dictionary];
  521. }
  522. libvlc_media_tracks_release(tracksInfo, count);
  523. return array;
  524. }
  525. - (BOOL)isMediaSizeSuitableForDevice
  526. {
  527. #if TARGET_OS_IPHONE
  528. // Trigger parsing if needed
  529. if (![self isParsed])
  530. [self synchronousParse];
  531. NSUInteger biggestWidth = 0;
  532. NSUInteger biggestHeight = 0;
  533. libvlc_media_track_t **tracksInfo;
  534. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  535. for (NSUInteger i = 0; i < count; i++) {
  536. switch (tracksInfo[i]->i_type) {
  537. case libvlc_track_video:
  538. if (tracksInfo[i]->video->i_width > biggestWidth)
  539. biggestWidth = tracksInfo[i]->video->i_width;
  540. if (tracksInfo[i]->video->i_height > biggestHeight)
  541. biggestHeight = tracksInfo[i]->video->i_height;
  542. break;
  543. default:
  544. break;
  545. }
  546. }
  547. if (biggestHeight > 0 && biggestWidth > 0) {
  548. size_t size;
  549. sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  550. char *answer = malloc(size);
  551. sysctlbyname("hw.machine", answer, &size, NULL, 0);
  552. NSString *currentMachine = @(answer);
  553. free(answer);
  554. NSUInteger totalNumberOfPixels = biggestWidth * biggestHeight;
  555. if ([currentMachine hasPrefix:@"iPhone2"] || [currentMachine hasPrefix:@"iPhone3"] || [currentMachine hasPrefix:@"iPad1"] || [currentMachine hasPrefix:@"iPod3"] || [currentMachine hasPrefix:@"iPod4"]) {
  556. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  557. return (totalNumberOfPixels < 600000); // between 480p and 720p
  558. } else if ([currentMachine hasPrefix:@"iPhone4"] || [currentMachine hasPrefix:@"iPad3,1"] || [currentMachine hasPrefix:@"iPad3,2"] || [currentMachine hasPrefix:@"iPad3,3"] || [currentMachine hasPrefix:@"iPod4"] || [currentMachine hasPrefix:@"iPad2"] || [currentMachine hasPrefix:@"iPod5"]) {
  559. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  560. return (totalNumberOfPixels < 922000); // 720p
  561. } else {
  562. // iPhone 5, iPad 4
  563. return (totalNumberOfPixels < 2074000); // 1080p
  564. }
  565. }
  566. #endif
  567. return YES;
  568. }
  569. - (NSString *)metadataForKey:(NSString *)key
  570. {
  571. if (!p_md)
  572. return nil;
  573. if (![self isParsed])
  574. [self synchronousParse];
  575. char *returnValue = libvlc_media_get_meta(p_md, [VLCMedia stringToMetaType:key]);
  576. if (!returnValue)
  577. return nil;
  578. NSString *actualReturnValue = @(returnValue);
  579. free(returnValue);
  580. return actualReturnValue;
  581. }
  582. - (void)setMetadata:(NSString *)data forKey:(NSString *)key
  583. {
  584. if (!p_md)
  585. return;
  586. libvlc_media_set_meta(p_md, [VLCMedia stringToMetaType:key], [data UTF8String]);
  587. }
  588. - (BOOL)saveMetadata
  589. {
  590. if (p_md)
  591. return libvlc_media_save_meta(p_md) != 0;
  592. return NO;
  593. }
  594. /******************************************************************************
  595. * Implementation VLCMedia ()
  596. */
  597. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  598. {
  599. static NSDictionary * stringToMetaDictionary = nil;
  600. // TODO: Thread safe-ize
  601. if (!stringToMetaDictionary) {
  602. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  603. stringToMetaDictionary =
  604. [NSDictionary dictionaryWithObjectsAndKeys:
  605. VLCStringToMeta(Title),
  606. VLCStringToMeta(Artist),
  607. VLCStringToMeta(Genre),
  608. VLCStringToMeta(Copyright),
  609. VLCStringToMeta(Album),
  610. VLCStringToMeta(TrackNumber),
  611. VLCStringToMeta(Description),
  612. VLCStringToMeta(Rating),
  613. VLCStringToMeta(Date),
  614. VLCStringToMeta(Setting),
  615. VLCStringToMeta(URL),
  616. VLCStringToMeta(Language),
  617. VLCStringToMeta(NowPlaying),
  618. VLCStringToMeta(Publisher),
  619. VLCStringToMeta(ArtworkURL),
  620. VLCStringToMeta(TrackID),
  621. VLCStringToMeta(TrackTotal),
  622. VLCStringToMeta(Director),
  623. VLCStringToMeta(Season),
  624. VLCStringToMeta(Episode),
  625. VLCStringToMeta(ShowName),
  626. VLCStringToMeta(Actors),
  627. VLCStringToMeta(AlbumArtist),
  628. VLCStringToMeta(DiscNumber),
  629. nil];
  630. #undef VLCStringToMeta
  631. }
  632. NSNumber * number = stringToMetaDictionary[string];
  633. return (libvlc_meta_t) (number ? [number intValue] : -1);
  634. }
  635. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  636. {
  637. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  638. VLCMetaToString(Title, type);
  639. VLCMetaToString(Artist, type);
  640. VLCMetaToString(Genre, type);
  641. VLCMetaToString(Copyright, type);
  642. VLCMetaToString(Album, type);
  643. VLCMetaToString(TrackNumber, type);
  644. VLCMetaToString(Description, type);
  645. VLCMetaToString(Rating, type);
  646. VLCMetaToString(Date, type);
  647. VLCMetaToString(Setting, type);
  648. VLCMetaToString(URL, type);
  649. VLCMetaToString(Language, type);
  650. VLCMetaToString(NowPlaying, type);
  651. VLCMetaToString(Publisher, type);
  652. VLCMetaToString(ArtworkURL, type);
  653. VLCMetaToString(TrackID, type);
  654. VLCMetaToString(TrackTotal, type);
  655. VLCMetaToString(Director, type);
  656. VLCMetaToString(Season, type);
  657. VLCMetaToString(Episode, type);
  658. VLCMetaToString(ShowName, type);
  659. VLCMetaToString(Actors, type);
  660. VLCMetaToString(AlbumArtist, type);
  661. VLCMetaToString(DiscNumber, type);
  662. #undef VLCMetaToString
  663. return nil;
  664. }
  665. - (void)initInternalMediaDescriptor
  666. {
  667. char * p_url = libvlc_media_get_mrl( p_md );
  668. if (!p_url)
  669. return;
  670. _url = [NSURL URLWithString:@(p_url)];
  671. if (!_url) /* Attempt to interpret as a file path then */
  672. _url = [NSURL fileURLWithPath:@(p_url)];
  673. free(p_url);
  674. libvlc_media_set_user_data(p_md, (__bridge void*)self);
  675. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md );
  676. if (p_em) {
  677. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, (__bridge void *)(self));
  678. libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, (__bridge void *)(self));
  679. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, (__bridge void *)(self));
  680. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, (__bridge void *)(self));
  681. libvlc_event_attach(p_em, libvlc_MediaParsedChanged, HandleMediaParsedChanged, (__bridge void *)(self));
  682. }
  683. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  684. if (p_mlist) {
  685. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  686. libvlc_media_list_release( p_mlist );
  687. }
  688. isParsed = libvlc_media_is_parsed(p_md) != 0;
  689. self.state = LibVLCStateToMediaState(libvlc_media_get_state( p_md ));
  690. }
  691. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  692. {
  693. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType] );
  694. NSString * newValue = psz_value ? @(psz_value) : nil;
  695. NSString * oldValue = [_metaDictionary valueForKey:metaType];
  696. free(psz_value);
  697. if (newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame)) {
  698. // Only fetch the art if needed. (ie, create the NSImage, if it was requested before)
  699. if (isArtFetched && [metaType isEqualToString:VLCMetaInformationArtworkURL]) {
  700. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  701. toTarget:self
  702. withObject:newValue];
  703. }
  704. [_metaDictionary setValue:newValue forKeyPath:metaType];
  705. }
  706. }
  707. #if !TARGET_OS_IPHONE
  708. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  709. {
  710. @autoreleasepool {
  711. NSImage * art = nil;
  712. if (anURL) {
  713. // Go ahead and load up the art work
  714. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  715. // Don't attempt to fetch artwork from remote. Core will do that alone
  716. if ([artUrl isFileURL])
  717. art = [[NSImage alloc] initWithContentsOfURL:artUrl];
  718. }
  719. // If anything was found, lets save it to the meta data dictionary
  720. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  721. }
  722. }
  723. - (void)setArtwork:(NSImage *)art
  724. {
  725. if (!art)
  726. [(NSMutableDictionary *)_metaDictionary removeObjectForKey:@"artwork"];
  727. else
  728. ((NSMutableDictionary *)_metaDictionary)[@"artwork"] = art;
  729. }
  730. #endif
  731. - (void)parseIfNeeded
  732. {
  733. if (![self isParsed])
  734. [self parse];
  735. }
  736. - (void)metaChanged:(NSString *)metaType
  737. {
  738. [self fetchMetaInformationFromLibVLCWithType:metaType];
  739. if ([_delegate respondsToSelector:@selector(mediaMetaDataDidChange:)])
  740. [_delegate mediaMetaDataDidChange:self];
  741. }
  742. - (void)subItemAdded
  743. {
  744. if (_subitems)
  745. return; /* Nothing to do */
  746. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  747. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  748. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  749. libvlc_media_list_release( p_mlist );
  750. }
  751. - (void)parsedChanged:(NSNumber *)isParsedAsNumber
  752. {
  753. [self willChangeValueForKey:@"parsed"];
  754. isParsed = [isParsedAsNumber boolValue];
  755. [self didChangeValueForKey:@"parsed"];
  756. // FIXME: Probably don't even call this if there is no delegate.
  757. if (!_delegate || !isParsed)
  758. return;
  759. if ([_delegate respondsToSelector:@selector(mediaDidFinishParsing:)])
  760. [_delegate mediaDidFinishParsing:self];
  761. }
  762. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  763. {
  764. [self setState: [newStateAsNumber intValue]];
  765. }
  766. #if TARGET_OS_IPHONE
  767. - (NSDictionary *)metaDictionary
  768. {
  769. if (!areOthersMetaFetched) {
  770. areOthersMetaFetched = YES;
  771. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  772. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtist];
  773. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationAlbum];
  774. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDate];
  775. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationGenre];
  776. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTrackNumber];
  777. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationNowPlaying];
  778. }
  779. if (!isArtURLFetched) {
  780. isArtURLFetched = YES;
  781. /* Force isArtURLFetched, that will trigger artwork download eventually
  782. * And all the other meta will be added through the libvlc event system */
  783. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  784. }
  785. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  786. }
  787. #else
  788. - (NSDictionary *)metaDictionary
  789. {
  790. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  791. }
  792. - (id)valueForKeyPath:(NSString *)keyPath
  793. {
  794. if (!isArtFetched && [keyPath isEqualToString:@"metaDictionary.artwork"]) {
  795. isArtFetched = YES;
  796. /* Force the retrieval of the artwork now that someone asked for it */
  797. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  798. } else if (!areOthersMetaFetched && [keyPath hasPrefix:@"metaDictionary."]) {
  799. areOthersMetaFetched = YES;
  800. /* Force VLCMetaInformationTitle, that will trigger preparsing
  801. * And all the other meta will be added through the libvlc event system */
  802. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  803. } else if (!isArtURLFetched && [keyPath hasPrefix:@"metaDictionary.artworkURL"]) {
  804. isArtURLFetched = YES;
  805. /* Force isArtURLFetched, that will trigger artwork download eventually
  806. * And all the other meta will be added through the libvlc event system */
  807. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  808. }
  809. return [super valueForKeyPath:keyPath];
  810. }
  811. #endif
  812. @end
  813. /******************************************************************************
  814. * Implementation VLCMedia (LibVLCBridging)
  815. */
  816. @implementation VLCMedia (LibVLCBridging)
  817. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  818. {
  819. return [[VLCMedia alloc] initWithLibVLCMediaDescriptor:md];
  820. }
  821. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  822. {
  823. libvlc_media_t * p_md;
  824. p_md = libvlc_media_duplicate([media libVLCMediaDescriptor]);
  825. for (NSString * key in [options allKeys]) {
  826. if (options[key] != [NSNull null])
  827. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, options[key]] UTF8String]);
  828. else
  829. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@", key] UTF8String]);
  830. }
  831. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  832. }
  833. - (id)initWithLibVLCMediaDescriptor:(void *)md
  834. {
  835. if (self = [super init]) {
  836. libvlc_media_retain(md);
  837. p_md = md;
  838. _metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  839. [self initInternalMediaDescriptor];
  840. }
  841. return self;
  842. }
  843. - (void *)libVLCMediaDescriptor
  844. {
  845. return p_md;
  846. }
  847. @end