VLCMedia.m 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. libvlc_media_parsed_status_t status = libvlc_media_get_parsed_status(p_md);
  277. while (!_length && !(status == VLCMediaParsedStatusFailed || status == VLCMediaParsedStatusDone) && [aDate timeIntervalSinceNow] > 0) {
  278. usleep( thread_sleep );
  279. status = libvlc_media_get_parsed_status(p_md);
  280. }
  281. // So we're done waiting, but sometimes we trap the fact that the parsing
  282. // was done before the length gets assigned, so lets go ahead and assign
  283. // it ourselves.
  284. if (!_length)
  285. return [self length];
  286. }
  287. return _length;
  288. }
  289. - (BOOL)isParsed
  290. {
  291. VLCMediaParsedStatus status = [self parsedStatus];
  292. return (status == VLCMediaParsedStatusFailed || status == VLCMediaParsedStatusDone) ? YES:NO;
  293. }
  294. - (VLCMediaParsedStatus)parsedStatus
  295. {
  296. if ( !p_md )
  297. return VLCMediaParsedStatusFailed;
  298. libvlc_media_parsed_status_t status = libvlc_media_get_parsed_status(p_md);
  299. return (VLCMediaParsedStatus)status;
  300. }
  301. - (void)parse
  302. {
  303. if (p_md)
  304. libvlc_media_parse_async(p_md);
  305. }
  306. - (void)synchronousParse
  307. {
  308. if (p_md)
  309. libvlc_media_parse(p_md);
  310. }
  311. - (int)parseWithOptions:(VLCMediaParsingOptions)options timeout:(int)timeoutValue
  312. {
  313. if (!p_md)
  314. return -1;
  315. // we are using the default time-out value
  316. return libvlc_media_parse_with_options(p_md,
  317. options,
  318. timeoutValue);
  319. }
  320. - (int)parseWithOptions:(VLCMediaParsingOptions)options
  321. {
  322. if (!p_md)
  323. return -1;
  324. // we are using the default time-out value
  325. return libvlc_media_parse_with_options(p_md,
  326. options,
  327. -1);
  328. }
  329. - (void)addOptions:(NSDictionary*)options
  330. {
  331. if (p_md) {
  332. [options enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
  333. if (![obj isKindOfClass:[NSNull class]])
  334. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, obj] UTF8String]);
  335. else
  336. libvlc_media_add_option(p_md, [key UTF8String]);
  337. }];
  338. }
  339. }
  340. - (NSDictionary*) stats
  341. {
  342. if (!p_md)
  343. return nil;
  344. libvlc_media_stats_t p_stats;
  345. libvlc_media_get_stats(p_md, &p_stats);
  346. return @{
  347. @"demuxBitrate" : @(p_stats.f_demux_bitrate),
  348. @"inputBitrate" : @(p_stats.f_input_bitrate),
  349. @"sendBitrate" : @(p_stats.f_send_bitrate),
  350. @"decodedAudio" : @(p_stats.i_decoded_audio),
  351. @"decodedVideo" : @(p_stats.i_decoded_video),
  352. @"demuxCorrupted" : @(p_stats.i_demux_corrupted),
  353. @"demuxDiscontinuity" : @(p_stats.i_demux_discontinuity),
  354. @"demuxReadBytes" : @(p_stats.i_demux_read_bytes),
  355. @"displayedPictures" : @(p_stats.i_displayed_pictures),
  356. @"lostAbuffers" : @(p_stats.i_lost_abuffers),
  357. @"lostPictures" : @(p_stats.i_lost_pictures),
  358. @"playedAbuffers" : @(p_stats.i_played_abuffers),
  359. @"readBytes" : @(p_stats.i_read_bytes),
  360. @"sentBytes" : @(p_stats.i_sent_bytes),
  361. @"sentPackets" : @(p_stats.i_sent_packets)
  362. };
  363. }
  364. - (NSInteger)numberOfReadBytesOnInput
  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_read_bytes;
  371. }
  372. - (float)inputBitrate
  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_input_bitrate;
  379. }
  380. - (NSInteger)numberOfReadBytesOnDemux
  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_demux_read_bytes;
  387. }
  388. - (float)demuxBitrate
  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.f_demux_bitrate;
  395. }
  396. - (NSInteger)numberOfDecodedVideoBlocks
  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_decoded_video;
  403. }
  404. - (NSInteger)numberOfDecodedAudioBlocks
  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_decoded_audio;
  411. }
  412. - (NSInteger)numberOfDisplayedPictures
  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_displayed_pictures;
  419. }
  420. - (NSInteger)numberOfLostPictures
  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_pictures;
  427. }
  428. - (NSInteger)numberOfPlayedAudioBuffers
  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_played_abuffers;
  435. }
  436. - (NSInteger)numberOfLostAudioBuffers
  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_lost_abuffers;
  443. }
  444. - (NSInteger)numberOfSentPackets
  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.i_sent_packets;
  451. }
  452. - (NSInteger)numberOfSentBytes
  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_sent_bytes;
  459. }
  460. - (float)streamOutputBitrate
  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.f_send_bitrate;
  467. }
  468. - (NSInteger)numberOfCorruptedDataPackets
  469. {
  470. if (!p_md)
  471. return 0;
  472. libvlc_media_stats_t p_stats;
  473. libvlc_media_get_stats(p_md, &p_stats);
  474. return p_stats.i_demux_corrupted;
  475. }
  476. - (NSInteger)numberOfDiscontinuties
  477. {
  478. if (!p_md)
  479. return 0;
  480. libvlc_media_stats_t p_stats;
  481. libvlc_media_get_stats(p_md, &p_stats);
  482. return p_stats.i_demux_discontinuity;
  483. }
  484. NSString *const VLCMediaTracksInformationCodec = @"codec"; // NSNumber
  485. NSString *const VLCMediaTracksInformationId = @"id"; // NSNumber
  486. NSString *const VLCMediaTracksInformationType = @"type"; // NSString
  487. NSString *const VLCMediaTracksInformationCodecProfile = @"profile"; // NSNumber
  488. NSString *const VLCMediaTracksInformationCodecLevel = @"level"; // NSNumber
  489. NSString *const VLCMediaTracksInformationTypeAudio = @"audio";
  490. NSString *const VLCMediaTracksInformationTypeVideo = @"video";
  491. NSString *const VLCMediaTracksInformationTypeText = @"text";
  492. NSString *const VLCMediaTracksInformationTypeUnknown = @"unknown";
  493. NSString *const VLCMediaTracksInformationBitrate = @"bitrate"; // NSNumber
  494. NSString *const VLCMediaTracksInformationLanguage = @"language"; // NSString
  495. NSString *const VLCMediaTracksInformationDescription = @"description"; // NSString
  496. NSString *const VLCMediaTracksInformationAudioChannelsNumber = @"channelsNumber"; // NSNumber
  497. NSString *const VLCMediaTracksInformationAudioRate = @"rate"; // NSNumber
  498. NSString *const VLCMediaTracksInformationVideoHeight = @"height"; // NSNumber
  499. NSString *const VLCMediaTracksInformationVideoWidth = @"width"; // NSNumber
  500. NSString *const VLCMediaTracksInformationSourceAspectRatio = @"sar_num"; // NSNumber
  501. NSString *const VLCMediaTracksInformationSourceAspectDenominator = @"sar_den"; // NSNumber
  502. NSString *const VLCMediaTracksInformationFrameRate = @"frame_rate_num"; // NSNumber
  503. NSString *const VLCMediaTracksInformationFrameRateDenominator = @"frame_rate_den"; // NSNumber
  504. NSString *const VLCMediaTracksInformationTextEncoding = @"encoding"; // NSString
  505. - (NSArray *)tracksInformation
  506. {
  507. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  508. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit)
  509. [self synchronousParse];
  510. libvlc_media_track_t **tracksInfo;
  511. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  512. NSMutableArray *array = [NSMutableArray array];
  513. for (NSUInteger i = 0; i < count; i++) {
  514. NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  515. @(tracksInfo[i]->i_codec),
  516. VLCMediaTracksInformationCodec,
  517. @(tracksInfo[i]->i_id),
  518. VLCMediaTracksInformationId,
  519. @(tracksInfo[i]->i_profile),
  520. VLCMediaTracksInformationCodecProfile,
  521. @(tracksInfo[i]->i_level),
  522. VLCMediaTracksInformationCodecLevel,
  523. @(tracksInfo[i]->i_bitrate),
  524. VLCMediaTracksInformationBitrate,
  525. nil];
  526. if (tracksInfo[i]->psz_language)
  527. dictionary[VLCMediaTracksInformationLanguage] = [NSString stringWithUTF8String:tracksInfo[i]->psz_language];
  528. if (tracksInfo[i]->psz_description)
  529. dictionary[VLCMediaTracksInformationDescription] = [NSString stringWithUTF8String:tracksInfo[i]->psz_description];
  530. NSString *type;
  531. switch (tracksInfo[i]->i_type) {
  532. case libvlc_track_audio:
  533. type = VLCMediaTracksInformationTypeAudio;
  534. dictionary[VLCMediaTracksInformationAudioChannelsNumber] = @(tracksInfo[i]->audio->i_channels);
  535. dictionary[VLCMediaTracksInformationAudioRate] = @(tracksInfo[i]->audio->i_rate);
  536. break;
  537. case libvlc_track_video:
  538. type = VLCMediaTracksInformationTypeVideo;
  539. dictionary[VLCMediaTracksInformationVideoWidth] = @(tracksInfo[i]->video->i_width);
  540. dictionary[VLCMediaTracksInformationVideoHeight] = @(tracksInfo[i]->video->i_height);
  541. dictionary[VLCMediaTracksInformationSourceAspectRatio] = @(tracksInfo[i]->video->i_sar_num);
  542. dictionary[VLCMediaTracksInformationSourceAspectDenominator] = @(tracksInfo[i]->video->i_sar_den);
  543. dictionary[VLCMediaTracksInformationFrameRate] = @(tracksInfo[i]->video->i_frame_rate_num);
  544. dictionary[VLCMediaTracksInformationFrameRateDenominator] = @(tracksInfo[i]->video->i_frame_rate_den);
  545. break;
  546. case libvlc_track_text:
  547. type = VLCMediaTracksInformationTypeText;
  548. if (tracksInfo[i]->subtitle->psz_encoding)
  549. dictionary[VLCMediaTracksInformationTextEncoding] = [NSString stringWithUTF8String: tracksInfo[i]->subtitle->psz_encoding];
  550. break;
  551. case libvlc_track_unknown:
  552. default:
  553. type = VLCMediaTracksInformationTypeUnknown;
  554. break;
  555. }
  556. [dictionary setValue:type forKey:VLCMediaTracksInformationType];
  557. [array addObject:dictionary];
  558. }
  559. libvlc_media_tracks_release(tracksInfo, count);
  560. return array;
  561. }
  562. - (BOOL)isMediaSizeSuitableForDevice
  563. {
  564. #if TARGET_OS_IPHONE
  565. // Trigger parsing if needed
  566. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  567. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit)
  568. [self synchronousParse];
  569. NSUInteger biggestWidth = 0;
  570. NSUInteger biggestHeight = 0;
  571. libvlc_media_track_t **tracksInfo;
  572. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  573. for (NSUInteger i = 0; i < count; i++) {
  574. switch (tracksInfo[i]->i_type) {
  575. case libvlc_track_video:
  576. if (tracksInfo[i]->video->i_width > biggestWidth)
  577. biggestWidth = tracksInfo[i]->video->i_width;
  578. if (tracksInfo[i]->video->i_height > biggestHeight)
  579. biggestHeight = tracksInfo[i]->video->i_height;
  580. break;
  581. default:
  582. break;
  583. }
  584. }
  585. if (biggestHeight > 0 && biggestWidth > 0) {
  586. size_t size;
  587. sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  588. char *answer = malloc(size);
  589. sysctlbyname("hw.machine", answer, &size, NULL, 0);
  590. NSString *currentMachine = @(answer);
  591. free(answer);
  592. NSUInteger totalNumberOfPixels = biggestWidth * biggestHeight;
  593. if ([currentMachine hasPrefix:@"iPhone2"] || [currentMachine hasPrefix:@"iPhone3"] || [currentMachine hasPrefix:@"iPad1"] || [currentMachine hasPrefix:@"iPod3"] || [currentMachine hasPrefix:@"iPod4"]) {
  594. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  595. return (totalNumberOfPixels < 600000); // between 480p and 720p
  596. } 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"]) {
  597. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  598. return (totalNumberOfPixels < 922000); // 720p
  599. } else {
  600. // iPhone 5, iPad 4
  601. return (totalNumberOfPixels < 2074000); // 1080p
  602. }
  603. }
  604. #endif
  605. return YES;
  606. }
  607. - (NSString *)metadataForKey:(NSString *)key
  608. {
  609. if (!p_md)
  610. return nil;
  611. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  612. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit)
  613. [self synchronousParse];
  614. char *returnValue = libvlc_media_get_meta(p_md, [VLCMedia stringToMetaType:key]);
  615. if (!returnValue)
  616. return nil;
  617. NSString *actualReturnValue = @(returnValue);
  618. free(returnValue);
  619. return actualReturnValue;
  620. }
  621. - (void)setMetadata:(NSString *)data forKey:(NSString *)key
  622. {
  623. if (!p_md)
  624. return;
  625. libvlc_media_set_meta(p_md, [VLCMedia stringToMetaType:key], [data UTF8String]);
  626. }
  627. - (BOOL)saveMetadata
  628. {
  629. if (p_md)
  630. return libvlc_media_save_meta(p_md) != 0;
  631. return NO;
  632. }
  633. /******************************************************************************
  634. * Implementation VLCMedia ()
  635. */
  636. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  637. {
  638. static NSDictionary * stringToMetaDictionary = nil;
  639. // TODO: Thread safe-ize
  640. if (!stringToMetaDictionary) {
  641. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  642. stringToMetaDictionary =
  643. [NSDictionary dictionaryWithObjectsAndKeys:
  644. VLCStringToMeta(Title),
  645. VLCStringToMeta(Artist),
  646. VLCStringToMeta(Genre),
  647. VLCStringToMeta(Copyright),
  648. VLCStringToMeta(Album),
  649. VLCStringToMeta(TrackNumber),
  650. VLCStringToMeta(Description),
  651. VLCStringToMeta(Rating),
  652. VLCStringToMeta(Date),
  653. VLCStringToMeta(Setting),
  654. VLCStringToMeta(URL),
  655. VLCStringToMeta(Language),
  656. VLCStringToMeta(NowPlaying),
  657. VLCStringToMeta(Publisher),
  658. VLCStringToMeta(ArtworkURL),
  659. VLCStringToMeta(TrackID),
  660. VLCStringToMeta(TrackTotal),
  661. VLCStringToMeta(Director),
  662. VLCStringToMeta(Season),
  663. VLCStringToMeta(Episode),
  664. VLCStringToMeta(ShowName),
  665. VLCStringToMeta(Actors),
  666. VLCStringToMeta(AlbumArtist),
  667. VLCStringToMeta(DiscNumber),
  668. nil];
  669. #undef VLCStringToMeta
  670. }
  671. NSNumber * number = stringToMetaDictionary[string];
  672. return (libvlc_meta_t) (number ? [number intValue] : -1);
  673. }
  674. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  675. {
  676. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  677. VLCMetaToString(Title, type);
  678. VLCMetaToString(Artist, type);
  679. VLCMetaToString(Genre, type);
  680. VLCMetaToString(Copyright, type);
  681. VLCMetaToString(Album, type);
  682. VLCMetaToString(TrackNumber, type);
  683. VLCMetaToString(Description, type);
  684. VLCMetaToString(Rating, type);
  685. VLCMetaToString(Date, type);
  686. VLCMetaToString(Setting, type);
  687. VLCMetaToString(URL, type);
  688. VLCMetaToString(Language, type);
  689. VLCMetaToString(NowPlaying, type);
  690. VLCMetaToString(Publisher, type);
  691. VLCMetaToString(ArtworkURL, type);
  692. VLCMetaToString(TrackID, type);
  693. VLCMetaToString(TrackTotal, type);
  694. VLCMetaToString(Director, type);
  695. VLCMetaToString(Season, type);
  696. VLCMetaToString(Episode, type);
  697. VLCMetaToString(ShowName, type);
  698. VLCMetaToString(Actors, type);
  699. VLCMetaToString(AlbumArtist, type);
  700. VLCMetaToString(DiscNumber, type);
  701. #undef VLCMetaToString
  702. return nil;
  703. }
  704. - (void)initInternalMediaDescriptor
  705. {
  706. char * p_url = libvlc_media_get_mrl( p_md );
  707. if (!p_url)
  708. return;
  709. NSString *urlString = [NSString stringWithUTF8String:p_url];
  710. if (!urlString) {
  711. free(p_url);
  712. return;
  713. }
  714. urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  715. if (!urlString) {
  716. free(p_url);
  717. return;
  718. }
  719. _url = [NSURL URLWithString:urlString];
  720. if (!_url) /* Attempt to interpret as a file path then */ {
  721. _url = [NSURL fileURLWithPath:urlString];
  722. if(!_url) {
  723. free(p_url);
  724. return;
  725. }
  726. }
  727. free(p_url);
  728. libvlc_media_set_user_data(p_md, (__bridge void*)self);
  729. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md );
  730. if (p_em) {
  731. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, (__bridge void *)(self));
  732. libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, (__bridge void *)(self));
  733. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, (__bridge void *)(self));
  734. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, (__bridge void *)(self));
  735. libvlc_event_attach(p_em, libvlc_MediaParsedChanged, HandleMediaParsedChanged, (__bridge void *)(self));
  736. }
  737. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  738. if (p_mlist) {
  739. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  740. libvlc_media_list_release( p_mlist );
  741. }
  742. self.state = LibVLCStateToMediaState(libvlc_media_get_state( p_md ));
  743. }
  744. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  745. {
  746. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType] );
  747. NSString * newValue = psz_value ? @(psz_value) : nil;
  748. NSString * oldValue = [_metaDictionary valueForKey:metaType];
  749. free(psz_value);
  750. if (newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame)) {
  751. #if !TARGET_OS_IPHONE
  752. // Only fetch the art if needed. (ie, create the NSImage, if it was requested before)
  753. if (isArtFetched && [metaType isEqualToString:VLCMetaInformationArtworkURL]) {
  754. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  755. toTarget:self
  756. withObject:newValue];
  757. }
  758. #endif
  759. [_metaDictionary setValue:newValue forKeyPath:metaType];
  760. }
  761. }
  762. #if !TARGET_OS_IPHONE
  763. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  764. {
  765. @autoreleasepool {
  766. NSImage * art = nil;
  767. if (anURL) {
  768. // Go ahead and load up the art work
  769. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  770. // Don't attempt to fetch artwork from remote. Core will do that alone
  771. if ([artUrl isFileURL])
  772. art = [[NSImage alloc] initWithContentsOfURL:artUrl];
  773. }
  774. // If anything was found, lets save it to the meta data dictionary
  775. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  776. }
  777. }
  778. - (void)setArtwork:(NSImage *)art
  779. {
  780. if (!art)
  781. [(NSMutableDictionary *)_metaDictionary removeObjectForKey:@"artwork"];
  782. else
  783. ((NSMutableDictionary *)_metaDictionary)[@"artwork"] = art;
  784. }
  785. #endif
  786. - (void)parseIfNeeded
  787. {
  788. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  789. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit)
  790. [self parseWithOptions:VLCMediaParseLocal | VLCMediaFetchLocal];
  791. }
  792. - (void)metaChanged:(NSString *)metaType
  793. {
  794. [self fetchMetaInformationFromLibVLCWithType:metaType];
  795. if ([_delegate respondsToSelector:@selector(mediaMetaDataDidChange:)])
  796. [_delegate mediaMetaDataDidChange:self];
  797. }
  798. - (void)subItemAdded
  799. {
  800. if (_subitems)
  801. return; /* Nothing to do */
  802. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  803. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  804. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  805. libvlc_media_list_release( p_mlist );
  806. }
  807. - (void)parsedChanged:(NSNumber *)isParsedAsNumber
  808. {
  809. [self willChangeValueForKey:@"parsedStatus"];
  810. [self parsedStatus];
  811. [self didChangeValueForKey:@"parsedStatus"];
  812. if (!_delegate)
  813. return;
  814. if ([_delegate respondsToSelector:@selector(mediaDidFinishParsing:)])
  815. [_delegate mediaDidFinishParsing:self];
  816. }
  817. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  818. {
  819. [self setState: [newStateAsNumber intValue]];
  820. }
  821. #if TARGET_OS_IPHONE
  822. - (NSDictionary *)metaDictionary
  823. {
  824. if (!areOthersMetaFetched) {
  825. areOthersMetaFetched = YES;
  826. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  827. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtist];
  828. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationAlbum];
  829. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDate];
  830. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationGenre];
  831. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTrackNumber];
  832. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDiscNumber];
  833. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationNowPlaying];
  834. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationLanguage];
  835. }
  836. if (!isArtURLFetched) {
  837. isArtURLFetched = YES;
  838. /* Force isArtURLFetched, that will trigger artwork download eventually
  839. * And all the other meta will be added through the libvlc event system */
  840. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  841. }
  842. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  843. }
  844. #else
  845. - (NSDictionary *)metaDictionary
  846. {
  847. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  848. }
  849. - (id)valueForKeyPath:(NSString *)keyPath
  850. {
  851. if (!isArtFetched && [keyPath isEqualToString:@"metaDictionary.artwork"]) {
  852. isArtFetched = YES;
  853. /* Force the retrieval of the artwork now that someone asked for it */
  854. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  855. } else if (!areOthersMetaFetched && [keyPath hasPrefix:@"metaDictionary."]) {
  856. areOthersMetaFetched = YES;
  857. /* Force VLCMetaInformationTitle, that will trigger preparsing
  858. * And all the other meta will be added through the libvlc event system */
  859. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  860. } else if (!isArtURLFetched && [keyPath hasPrefix:@"metaDictionary.artworkURL"]) {
  861. isArtURLFetched = YES;
  862. /* Force isArtURLFetched, that will trigger artwork download eventually
  863. * And all the other meta will be added through the libvlc event system */
  864. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  865. }
  866. return [super valueForKeyPath:keyPath];
  867. }
  868. #endif
  869. @end
  870. /******************************************************************************
  871. * Implementation VLCMedia (LibVLCBridging)
  872. */
  873. @implementation VLCMedia (LibVLCBridging)
  874. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  875. {
  876. return [[VLCMedia alloc] initWithLibVLCMediaDescriptor:md];
  877. }
  878. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  879. {
  880. libvlc_media_t * p_md;
  881. p_md = libvlc_media_duplicate([media libVLCMediaDescriptor]);
  882. for (NSString * key in [options allKeys]) {
  883. if (options[key] != [NSNull null])
  884. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, options[key]] UTF8String]);
  885. else
  886. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@", key] UTF8String]);
  887. }
  888. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  889. }
  890. - (id)initWithLibVLCMediaDescriptor:(void *)md
  891. {
  892. if (self = [super init]) {
  893. libvlc_media_retain(md);
  894. p_md = md;
  895. _metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  896. [self initInternalMediaDescriptor];
  897. }
  898. return self;
  899. }
  900. - (void *)libVLCMediaDescriptor
  901. {
  902. return p_md;
  903. }
  904. @end