VLCMedia.m 36 KB

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