VLCMedia.m 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. /* Notification Messages */
  53. NSString *const VLCMediaMetaChanged = @"VLCMediaMetaChanged";
  54. /******************************************************************************
  55. * @property (readwrite)
  56. */
  57. @interface VLCMedia ()
  58. {
  59. void * p_md; //< Internal media descriptor instance
  60. NSURL * url; //< URL (MRL) for this media resource
  61. VLCMediaList * subitems; //< Sub list of items
  62. VLCTime * length; //< Cached duration of the media
  63. NSMutableDictionary * metaDictionary; //< Meta data storage
  64. BOOL isArtFetched; //< Value used to determine of the artwork has been parsed
  65. BOOL areOthersMetaFetched; //< Value used to determine of the other meta has been parsed
  66. BOOL isArtURLFetched; //< Value used to determine of the other meta has been preparsed
  67. VLCMediaState state; //< Current state of the media
  68. BOOL isParsed;
  69. }
  70. @property (readwrite) VLCMediaState state;
  71. @end
  72. /******************************************************************************
  73. * Interface (Private)
  74. */
  75. // TODO: Documentation
  76. @interface VLCMedia (Private)
  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. + (id)mediaWithURL:(NSURL *)anURL;
  159. {
  160. return [[VLCMedia alloc] initWithURL:anURL];
  161. }
  162. + (id)mediaWithPath:(NSString *)aPath;
  163. {
  164. return [[VLCMedia alloc] initWithPath:aPath];
  165. }
  166. + (id)mediaAsNodeWithName:(NSString *)aName;
  167. {
  168. return [[VLCMedia alloc] initAsNodeWithName:aName];
  169. }
  170. - (id)initWithPath:(NSString *)aPath
  171. {
  172. return [self initWithURL:[NSURL fileURLWithPath:aPath isDirectory:NO]];
  173. }
  174. - (id)initWithURL:(NSURL *)anURL
  175. {
  176. if (self = [super init]) {
  177. VLCLibrary *library = [VLCLibrary sharedLibrary];
  178. NSAssert(library.instance, @"no library instance when creating media");
  179. p_md = libvlc_media_new_location(library.instance, [[anURL absoluteString] UTF8String]);
  180. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  181. // This value is set whenever the demuxer figures out what the length is.
  182. // TODO: Easy way to tell the length of the movie without having to instiate the demuxer. Maybe cached info?
  183. length = nil;
  184. [self initInternalMediaDescriptor];
  185. }
  186. return self;
  187. }
  188. - (id)initAsNodeWithName:(NSString *)aName
  189. {
  190. if (self = [super init]) {
  191. p_md = libvlc_media_new_as_node([VLCLibrary sharedInstance],
  192. [aName UTF8String]);
  193. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  194. // This value is set whenever the demuxer figures out what the length is.
  195. // TODO: Easy way to tell the length of the movie without having to instiate the demuxer. Maybe cached info?
  196. length = nil;
  197. [self initInternalMediaDescriptor];
  198. }
  199. return self;
  200. }
  201. - (void)dealloc
  202. {
  203. libvlc_event_manager_t * p_em = libvlc_media_event_manager(p_md);
  204. libvlc_event_detach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, (__bridge void *)(self));
  205. libvlc_event_detach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, (__bridge void *)(self));
  206. libvlc_event_detach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, (__bridge void *)(self));
  207. libvlc_event_detach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, (__bridge void *)(self));
  208. libvlc_event_detach(p_em, libvlc_MediaParsedChanged, HandleMediaParsedChanged, (__bridge void *)(self));
  209. [[VLCEventManager sharedManager] cancelCallToObject:self];
  210. // Testing to see if the pointer exists is not required, if the pointer is null
  211. // then the release message is not sent to it.
  212. _delegate = nil;
  213. libvlc_media_release( p_md );
  214. }
  215. - (NSString *)description
  216. {
  217. NSString * result = metaDictionary[VLCMetaInformationTitle];
  218. return [NSString stringWithFormat:@"<%@ %p> %@", [self class], self, (result ? result : [url absoluteString])];
  219. }
  220. - (NSComparisonResult)compare:(VLCMedia *)media
  221. {
  222. if (self == media)
  223. return NSOrderedSame;
  224. if (!media)
  225. return NSOrderedDescending;
  226. return p_md == [media libVLCMediaDescriptor] ? NSOrderedSame : NSOrderedAscending;
  227. }
  228. - (VLCTime *)length
  229. {
  230. if (!length) {
  231. // Try figuring out what the length is
  232. long long duration = libvlc_media_get_duration( p_md );
  233. if (duration > -1) {
  234. length = [VLCTime timeWithNumber:@(duration)];
  235. return length;
  236. }
  237. return [VLCTime nullTime];
  238. }
  239. return length;
  240. }
  241. - (VLCTime *)lengthWaitUntilDate:(NSDate *)aDate
  242. {
  243. static const long long thread_sleep = 10000;
  244. if (!length) {
  245. // Force parsing of this item.
  246. [self parseIfNeeded];
  247. // wait until we are preparsed
  248. while (!length && !libvlc_media_is_parsed(p_md) && [aDate timeIntervalSinceNow] > 0)
  249. usleep( thread_sleep );
  250. // So we're done waiting, but sometimes we trap the fact that the parsing
  251. // was done before the length gets assigned, so lets go ahead and assign
  252. // it ourselves.
  253. if (!length)
  254. return [self length];
  255. }
  256. return length;
  257. }
  258. - (BOOL)isParsed
  259. {
  260. return isParsed;
  261. }
  262. - (void)parse
  263. {
  264. if (p_md)
  265. libvlc_media_parse_async(p_md);
  266. }
  267. - (void)synchronousParse
  268. {
  269. if (p_md)
  270. libvlc_media_parse(p_md);
  271. }
  272. - (void)addOptions:(NSDictionary*)options
  273. {
  274. if (p_md) {
  275. for (NSString * key in [options allKeys]) {
  276. if (options[key] != [NSNull null])
  277. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, options[key]] UTF8String]);
  278. else
  279. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@", key] UTF8String]);
  280. }
  281. }
  282. }
  283. - (NSDictionary*) stats
  284. {
  285. if (!p_md)
  286. return NULL;
  287. NSMutableDictionary *d = [NSMutableDictionary dictionary];
  288. libvlc_media_stats_t p_stats;
  289. libvlc_media_get_stats(p_md, &p_stats);
  290. d[@"demuxBitrate"] = @(p_stats.f_demux_bitrate);
  291. d[@"inputBitrate"] = @(p_stats.f_input_bitrate);
  292. d[@"sendBitrate"] = @(p_stats.f_send_bitrate);
  293. d[@"decodedAudio"] = @(p_stats.i_decoded_audio);
  294. d[@"decodedVideo"] = @(p_stats.i_decoded_video);
  295. d[@"demuxCorrupted"] = @(p_stats.i_demux_corrupted);
  296. d[@"demuxDiscontinuity"] = @(p_stats.i_demux_discontinuity);
  297. d[@"demuxReadBytes"] = @(p_stats.i_demux_read_bytes);
  298. d[@"displayedPictures"] = @(p_stats.i_displayed_pictures);
  299. d[@"lostAbuffers"] = @(p_stats.i_lost_abuffers);
  300. d[@"lostPictures"] = @(p_stats.i_lost_pictures);
  301. d[@"playedAbuffers"] = @(p_stats.i_played_abuffers);
  302. d[@"readBytes"] = @(p_stats.i_read_bytes);
  303. d[@"sentBytes"] = @(p_stats.i_sent_bytes);
  304. d[@"sentPackets"] = @(p_stats.i_sent_packets);
  305. return d;
  306. }
  307. - (NSInteger)numberOfReadBytesOnInput
  308. {
  309. if (!p_md)
  310. return 0;
  311. libvlc_media_stats_t p_stats;
  312. libvlc_media_get_stats(p_md, &p_stats);
  313. return p_stats.i_read_bytes;
  314. }
  315. - (float)inputBitrate
  316. {
  317. if (!p_md)
  318. return .0;
  319. libvlc_media_stats_t p_stats;
  320. libvlc_media_get_stats(p_md, &p_stats);
  321. return p_stats.f_input_bitrate;
  322. }
  323. - (NSInteger)numberOfReadBytesOnDemux
  324. {
  325. if (!p_md)
  326. return 0;
  327. libvlc_media_stats_t p_stats;
  328. libvlc_media_get_stats(p_md, &p_stats);
  329. return p_stats.i_demux_read_bytes;
  330. }
  331. - (float)demuxBitrate
  332. {
  333. if (!p_md)
  334. return .0;
  335. libvlc_media_stats_t p_stats;
  336. libvlc_media_get_stats(p_md, &p_stats);
  337. return p_stats.f_demux_bitrate;
  338. }
  339. - (NSInteger)numberOfDecodedVideoBlocks
  340. {
  341. if (!p_md)
  342. return 0;
  343. libvlc_media_stats_t p_stats;
  344. libvlc_media_get_stats(p_md, &p_stats);
  345. return p_stats.i_decoded_video;
  346. }
  347. - (NSInteger)numberOfDecodedAudioBlocks
  348. {
  349. if (!p_md)
  350. return 0;
  351. libvlc_media_stats_t p_stats;
  352. libvlc_media_get_stats(p_md, &p_stats);
  353. return p_stats.i_decoded_audio;
  354. }
  355. - (NSInteger)numberOfDisplayedPictures
  356. {
  357. if (!p_md)
  358. return 0;
  359. libvlc_media_stats_t p_stats;
  360. libvlc_media_get_stats(p_md, &p_stats);
  361. return p_stats.i_displayed_pictures;
  362. }
  363. - (NSInteger)numberOfLostPictures
  364. {
  365. if (!p_md)
  366. return 0;
  367. libvlc_media_stats_t p_stats;
  368. libvlc_media_get_stats(p_md, &p_stats);
  369. return p_stats.i_lost_pictures;
  370. }
  371. - (NSInteger)numberOfPlayedAudioBuffers
  372. {
  373. if (!p_md)
  374. return 0;
  375. libvlc_media_stats_t p_stats;
  376. libvlc_media_get_stats(p_md, &p_stats);
  377. return p_stats.i_played_abuffers;
  378. }
  379. - (NSInteger)numberOfLostAudioBuffers
  380. {
  381. if (!p_md)
  382. return 0;
  383. libvlc_media_stats_t p_stats;
  384. libvlc_media_get_stats(p_md, &p_stats);
  385. return p_stats.i_lost_abuffers;
  386. }
  387. - (NSInteger)numberOfSentPackets
  388. {
  389. if (!p_md)
  390. return 0;
  391. libvlc_media_stats_t p_stats;
  392. libvlc_media_get_stats(p_md, &p_stats);
  393. return p_stats.i_sent_packets;
  394. }
  395. - (NSInteger)numberOfSentBytes
  396. {
  397. if (!p_md)
  398. return 0;
  399. libvlc_media_stats_t p_stats;
  400. libvlc_media_get_stats(p_md, &p_stats);
  401. return p_stats.i_sent_bytes;
  402. }
  403. - (float)streamOutputBitrate
  404. {
  405. if (!p_md)
  406. return .0;
  407. libvlc_media_stats_t p_stats;
  408. libvlc_media_get_stats(p_md, &p_stats);
  409. return p_stats.f_send_bitrate;
  410. }
  411. - (NSInteger)numberOfCorruptedDataPackets
  412. {
  413. if (!p_md)
  414. return 0;
  415. libvlc_media_stats_t p_stats;
  416. libvlc_media_get_stats(p_md, &p_stats);
  417. return p_stats.i_demux_corrupted;
  418. }
  419. - (NSInteger)numberOfDiscontinuties
  420. {
  421. if (!p_md)
  422. return 0;
  423. libvlc_media_stats_t p_stats;
  424. libvlc_media_get_stats(p_md, &p_stats);
  425. return p_stats.i_demux_discontinuity;
  426. }
  427. NSString *const VLCMediaTracksInformationCodec = @"codec"; // NSNumber
  428. NSString *const VLCMediaTracksInformationId = @"id"; // NSNumber
  429. NSString *const VLCMediaTracksInformationType = @"type"; // NSString
  430. NSString *const VLCMediaTracksInformationCodecProfile = @"profile"; // NSNumber
  431. NSString *const VLCMediaTracksInformationCodecLevel = @"level"; // NSNumber
  432. NSString *const VLCMediaTracksInformationTypeAudio = @"audio";
  433. NSString *const VLCMediaTracksInformationTypeVideo = @"video";
  434. NSString *const VLCMediaTracksInformationTypeText = @"text";
  435. NSString *const VLCMediaTracksInformationTypeUnknown = @"unknown";
  436. NSString *const VLCMediaTracksInformationBitrate = @"bitrate"; // NSNumber
  437. NSString *const VLCMediaTracksInformationLanguage = @"language"; // NSString
  438. NSString *const VLCMediaTracksInformationDescription = @"description"; // NSString
  439. NSString *const VLCMediaTracksInformationAudioChannelsNumber = @"channelsNumber"; // NSNumber
  440. NSString *const VLCMediaTracksInformationAudioRate = @"rate"; // NSNumber
  441. NSString *const VLCMediaTracksInformationVideoHeight = @"height"; // NSNumber
  442. NSString *const VLCMediaTracksInformationVideoWidth = @"width"; // NSNumber
  443. NSString *const VLCMediaTracksInformationSourceAspectRatio = @"sar_num"; // NSNumber
  444. NSString *const VLCMediaTracksInformationSourceAspectDenominator = @"sar_den"; // NSNumber
  445. NSString *const VLCMediaTracksInformationFrameRate = @"frame_rate_num"; // NSNumber
  446. NSString *const VLCMediaTracksInformationFrameRateDenominator = @"frame_rate_den"; // NSNumber
  447. NSString *const VLCMediaTracksInformationTextEncoding = @"encoding"; // NSString
  448. - (NSArray *)tracksInformation
  449. {
  450. [self synchronousParse];
  451. libvlc_media_track_t **tracksInfo;
  452. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  453. NSMutableArray *array = [NSMutableArray array];
  454. for (NSUInteger i = 0; i < count; i++) {
  455. NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  456. @(tracksInfo[i]->i_codec),
  457. VLCMediaTracksInformationCodec,
  458. @(tracksInfo[i]->i_id),
  459. VLCMediaTracksInformationId,
  460. @(tracksInfo[i]->i_profile),
  461. VLCMediaTracksInformationCodecProfile,
  462. @(tracksInfo[i]->i_level),
  463. VLCMediaTracksInformationCodecLevel,
  464. @(tracksInfo[i]->i_bitrate),
  465. VLCMediaTracksInformationBitrate,
  466. nil];
  467. if (tracksInfo[i]->psz_language)
  468. dictionary[VLCMediaTracksInformationLanguage] = [NSString stringWithFormat:@"%s",tracksInfo[i]->psz_language];
  469. if (tracksInfo[i]->psz_description)
  470. dictionary[VLCMediaTracksInformationDescription] = [NSString stringWithFormat:@"%s",tracksInfo[i]->psz_description];
  471. NSString *type;
  472. switch (tracksInfo[i]->i_type) {
  473. case libvlc_track_audio:
  474. type = VLCMediaTracksInformationTypeAudio;
  475. dictionary[VLCMediaTracksInformationAudioChannelsNumber] = @(tracksInfo[i]->audio->i_channels);
  476. dictionary[VLCMediaTracksInformationAudioRate] = @(tracksInfo[i]->audio->i_rate);
  477. break;
  478. case libvlc_track_video:
  479. type = VLCMediaTracksInformationTypeVideo;
  480. dictionary[VLCMediaTracksInformationVideoWidth] = @(tracksInfo[i]->video->i_width);
  481. dictionary[VLCMediaTracksInformationVideoHeight] = @(tracksInfo[i]->video->i_height);
  482. dictionary[VLCMediaTracksInformationSourceAspectRatio] = @(tracksInfo[i]->video->i_sar_num);
  483. dictionary[VLCMediaTracksInformationSourceAspectDenominator] = @(tracksInfo[i]->video->i_sar_den);
  484. dictionary[VLCMediaTracksInformationFrameRate] = @(tracksInfo[i]->video->i_frame_rate_num);
  485. dictionary[VLCMediaTracksInformationFrameRateDenominator] = @(tracksInfo[i]->video->i_frame_rate_den);
  486. break;
  487. case libvlc_track_text:
  488. type = VLCMediaTracksInformationTypeText;
  489. if (tracksInfo[i]->subtitle->psz_encoding)
  490. dictionary[VLCMediaTracksInformationTextEncoding] = [NSString stringWithFormat:@"%s", tracksInfo[i]->subtitle->psz_encoding];
  491. break;
  492. case libvlc_track_unknown:
  493. default:
  494. type = VLCMediaTracksInformationTypeUnknown;
  495. break;
  496. }
  497. [dictionary setValue:type forKey:VLCMediaTracksInformationType];
  498. [array addObject:dictionary];
  499. }
  500. libvlc_media_tracks_release(tracksInfo, count);
  501. return array;
  502. }
  503. - (BOOL)isMediaSizeSuitableForDevice
  504. {
  505. #if TARGET_OS_IPHONE
  506. // Trigger parsing if needed
  507. if (![self isParsed])
  508. [self synchronousParse];
  509. NSUInteger biggestWidth = 0;
  510. NSUInteger biggestHeight = 0;
  511. libvlc_media_track_t **tracksInfo;
  512. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  513. for (NSUInteger i = 0; i < count; i++) {
  514. switch (tracksInfo[i]->i_type) {
  515. case libvlc_track_video:
  516. if (tracksInfo[i]->video->i_width > biggestWidth)
  517. biggestWidth = tracksInfo[i]->video->i_width;
  518. if (tracksInfo[i]->video->i_height > biggestHeight)
  519. biggestHeight = tracksInfo[i]->video->i_height;
  520. break;
  521. default:
  522. break;
  523. }
  524. }
  525. if (biggestHeight > 0 && biggestWidth > 0) {
  526. size_t size;
  527. sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  528. char *answer = malloc(size);
  529. sysctlbyname("hw.machine", answer, &size, NULL, 0);
  530. NSString *currentMachine = @(answer);
  531. free(answer);
  532. NSUInteger totalNumberOfPixels = biggestWidth * biggestHeight;
  533. if ([currentMachine hasPrefix:@"iPhone2"] || [currentMachine hasPrefix:@"iPhone3"] || [currentMachine hasPrefix:@"iPad1"] || [currentMachine hasPrefix:@"iPod3"] || [currentMachine hasPrefix:@"iPod4"]) {
  534. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  535. return (totalNumberOfPixels < 600000); // between 480p and 720p
  536. } 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"]) {
  537. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  538. return (totalNumberOfPixels < 922000); // 720p
  539. } else {
  540. // iPhone 5, iPad 4
  541. return (totalNumberOfPixels < 2074000); // 1080p
  542. }
  543. }
  544. #endif
  545. return YES;
  546. }
  547. @synthesize url;
  548. @synthesize subitems;
  549. - (NSString *)metadataForKey:(NSString *)key
  550. {
  551. if (!p_md)
  552. return NULL;
  553. if (![self isParsed])
  554. [self synchronousParse];
  555. char *returnValue = libvlc_media_get_meta(p_md, [VLCMedia stringToMetaType:key]);
  556. if (!returnValue)
  557. return NULL;
  558. NSString *actualReturnValue = [NSString stringWithUTF8String:returnValue];
  559. free(returnValue);
  560. return actualReturnValue;
  561. }
  562. - (void)setMetadata:(NSString *)data forKey:(NSString *)key
  563. {
  564. if (!p_md)
  565. return;
  566. libvlc_media_set_meta(p_md, [VLCMedia stringToMetaType:key], [data UTF8String]);
  567. }
  568. - (BOOL)saveMetadata
  569. {
  570. if (p_md)
  571. return libvlc_media_save_meta(p_md);
  572. return NO;
  573. }
  574. @synthesize metaDictionary;
  575. @synthesize state;
  576. @end
  577. /******************************************************************************
  578. * Implementation VLCMedia (LibVLCBridging)
  579. */
  580. @implementation VLCMedia (LibVLCBridging)
  581. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  582. {
  583. return [[VLCMedia alloc] initWithLibVLCMediaDescriptor:md];
  584. }
  585. - (id)initWithLibVLCMediaDescriptor:(void *)md
  586. {
  587. if (self = [super init]) {
  588. libvlc_media_retain(md);
  589. p_md = md;
  590. metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  591. [self initInternalMediaDescriptor];
  592. }
  593. return self;
  594. }
  595. - (void *)libVLCMediaDescriptor
  596. {
  597. return p_md;
  598. }
  599. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  600. {
  601. libvlc_media_t * p_md;
  602. p_md = libvlc_media_duplicate([media libVLCMediaDescriptor]);
  603. for (NSString * key in [options allKeys]) {
  604. if (options[key] != [NSNull null])
  605. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, options[key]] UTF8String]);
  606. else
  607. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@", key] UTF8String]);
  608. }
  609. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  610. }
  611. @end
  612. /******************************************************************************
  613. * Implementation VLCMedia (Private)
  614. */
  615. @implementation VLCMedia (Private)
  616. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  617. {
  618. static NSDictionary * stringToMetaDictionary = nil;
  619. // TODO: Thread safe-ize
  620. if (!stringToMetaDictionary) {
  621. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  622. stringToMetaDictionary =
  623. [NSDictionary dictionaryWithObjectsAndKeys:
  624. VLCStringToMeta(Title),
  625. VLCStringToMeta(Artist),
  626. VLCStringToMeta(Genre),
  627. VLCStringToMeta(Copyright),
  628. VLCStringToMeta(Album),
  629. VLCStringToMeta(TrackNumber),
  630. VLCStringToMeta(Description),
  631. VLCStringToMeta(Rating),
  632. VLCStringToMeta(Date),
  633. VLCStringToMeta(Setting),
  634. VLCStringToMeta(URL),
  635. VLCStringToMeta(Language),
  636. VLCStringToMeta(NowPlaying),
  637. VLCStringToMeta(Publisher),
  638. VLCStringToMeta(ArtworkURL),
  639. VLCStringToMeta(TrackID),
  640. nil];
  641. #undef VLCStringToMeta
  642. }
  643. NSNumber * number = stringToMetaDictionary[string];
  644. return number ? [number intValue] : -1;
  645. }
  646. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  647. {
  648. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  649. VLCMetaToString(Title, type);
  650. VLCMetaToString(Artist, type);
  651. VLCMetaToString(Genre, type);
  652. VLCMetaToString(Copyright, type);
  653. VLCMetaToString(Album, type);
  654. VLCMetaToString(TrackNumber, type);
  655. VLCMetaToString(Description, type);
  656. VLCMetaToString(Rating, type);
  657. VLCMetaToString(Date, type);
  658. VLCMetaToString(Setting, type);
  659. VLCMetaToString(URL, type);
  660. VLCMetaToString(Language, type);
  661. VLCMetaToString(NowPlaying, type);
  662. VLCMetaToString(Publisher, type);
  663. VLCMetaToString(ArtworkURL, type);
  664. VLCMetaToString(TrackID, type);
  665. #undef VLCMetaToString
  666. return nil;
  667. }
  668. - (void)initInternalMediaDescriptor
  669. {
  670. char * p_url = libvlc_media_get_mrl( p_md );
  671. if (!p_url)
  672. return;
  673. url = [NSURL URLWithString:@(p_url)];
  674. if (!url) /* Attempt to interpret as a file path then */
  675. url = [NSURL fileURLWithPath:@(p_url)];
  676. free(p_url);
  677. libvlc_media_set_user_data(p_md, (__bridge void*)self);
  678. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md );
  679. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, (__bridge void *)(self));
  680. libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, (__bridge void *)(self));
  681. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, (__bridge void *)(self));
  682. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, (__bridge void *)(self));
  683. libvlc_event_attach(p_em, libvlc_MediaParsedChanged, HandleMediaParsedChanged, (__bridge void *)(self));
  684. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  685. if (!p_mlist)
  686. subitems = nil;
  687. else {
  688. subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  689. libvlc_media_list_release( p_mlist );
  690. }
  691. isParsed = libvlc_media_is_parsed(p_md);
  692. state = LibVLCStateToMediaState(libvlc_media_get_state( p_md ));
  693. }
  694. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  695. {
  696. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType] );
  697. NSString * newValue = psz_value ? @(psz_value) : nil;
  698. NSString * oldValue = [metaDictionary valueForKey:metaType];
  699. free(psz_value);
  700. if (newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame)) {
  701. // Only fetch the art if needed. (ie, create the NSImage, if it was requested before)
  702. if (isArtFetched && [metaType isEqualToString:VLCMetaInformationArtworkURL]) {
  703. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  704. toTarget:self
  705. withObject:newValue];
  706. }
  707. [metaDictionary setValue:newValue forKeyPath:metaType];
  708. }
  709. }
  710. #if !TARGET_OS_IPHONE
  711. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  712. {
  713. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  714. NSImage * art = nil;
  715. if (anURL) {
  716. // Go ahead and load up the art work
  717. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  718. // Don't attempt to fetch artwork from remote. Core will do that alone
  719. if ([artUrl isFileURL])
  720. art = [[[NSImage alloc] initWithContentsOfURL:artUrl] autorelease];
  721. }
  722. // If anything was found, lets save it to the meta data dictionary
  723. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  724. [pool release];
  725. }
  726. - (void)setArtwork:(NSImage *)art
  727. {
  728. if (!art) {
  729. [metaDictionary removeObjectForKey:@"artwork"];
  730. return;
  731. }
  732. [metaDictionary setObject:art forKey:@"artwork"];
  733. }
  734. #endif
  735. - (void)parseIfNeeded
  736. {
  737. if (![self isParsed])
  738. [self parse];
  739. }
  740. - (void)metaChanged:(NSString *)metaType
  741. {
  742. [self fetchMetaInformationFromLibVLCWithType:metaType];
  743. if ([_delegate respondsToSelector:@selector(mediaMetaDataDidChange:)])
  744. [_delegate mediaMetaDataDidChange:self];
  745. }
  746. - (void)subItemAdded
  747. {
  748. if (subitems)
  749. return; /* Nothing to do */
  750. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  751. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  752. [self willChangeValueForKey:@"subitems"];
  753. subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  754. [self didChangeValueForKey:@"subitems"];
  755. libvlc_media_list_release( p_mlist );
  756. }
  757. - (void)parsedChanged:(NSNumber *)isParsedAsNumber
  758. {
  759. [self willChangeValueForKey:@"parsed"];
  760. isParsed = [isParsedAsNumber boolValue];
  761. [self didChangeValueForKey:@"parsed"];
  762. // FIXME: Probably don't even call this if there is no delegate.
  763. if (!_delegate || !isParsed)
  764. return;
  765. if ([_delegate respondsToSelector:@selector(mediaDidFinishParsing:)])
  766. [_delegate mediaDidFinishParsing:self];
  767. }
  768. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  769. {
  770. [self setState: [newStateAsNumber intValue]];
  771. }
  772. #if TARGET_OS_IPHONE
  773. - (NSDictionary *)metaDictionary
  774. {
  775. if (!areOthersMetaFetched) {
  776. areOthersMetaFetched = YES;
  777. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  778. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtist];
  779. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationAlbum];
  780. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDate];
  781. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationGenre];
  782. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTrackNumber];
  783. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationNowPlaying];
  784. }
  785. if (!isArtURLFetched) {
  786. isArtURLFetched = YES;
  787. /* Force isArtURLFetched, that will trigger artwork download eventually
  788. * And all the other meta will be added through the libvlc event system */
  789. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  790. }
  791. return metaDictionary;
  792. }
  793. #else
  794. - (id)valueForKeyPath:(NSString *)keyPath
  795. {
  796. if (!isArtFetched && [keyPath isEqualToString:@"metaDictionary.artwork"]) {
  797. isArtFetched = YES;
  798. /* Force the retrieval of the artwork now that someone asked for it */
  799. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  800. } else if (!areOthersMetaFetched && [keyPath hasPrefix:@"metaDictionary."]) {
  801. areOthersMetaFetched = YES;
  802. /* Force VLCMetaInformationTitle, that will trigger preparsing
  803. * And all the other meta will be added through the libvlc event system */
  804. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  805. } else if (!isArtURLFetched && [keyPath hasPrefix:@"metaDictionary.artworkURL"]) {
  806. isArtURLFetched = YES;
  807. /* Force isArtURLFetched, that will trigger artwork download eventually
  808. * And all the other meta will be added through the libvlc event system */
  809. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  810. }
  811. return [super valueForKeyPath:keyPath];
  812. }
  813. #endif
  814. @end
  815. /******************************************************************************
  816. * Implementation VLCMedia (VLCMediaPlayerBridging)
  817. */
  818. @implementation VLCMedia (VLCMediaPlayerBridging)
  819. - (void)setLength:(VLCTime *)value
  820. {
  821. if (length && value && [length compare:value] == NSOrderedSame)
  822. return;
  823. length = value ? value : nil;
  824. }
  825. @end