VLCMedia.m 35 KB

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