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