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; ///< Dictionary to cache metadata read from libvlc
  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 parseWithOptions:VLCMediaParseLocal|VLCMediaParseNetwork];
  510. return @[];
  511. }
  512. libvlc_media_track_t **tracksInfo;
  513. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  514. NSMutableArray *array = [NSMutableArray array];
  515. for (NSUInteger i = 0; i < count; i++) {
  516. NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  517. @(tracksInfo[i]->i_codec),
  518. VLCMediaTracksInformationCodec,
  519. @(tracksInfo[i]->i_id),
  520. VLCMediaTracksInformationId,
  521. @(tracksInfo[i]->i_profile),
  522. VLCMediaTracksInformationCodecProfile,
  523. @(tracksInfo[i]->i_level),
  524. VLCMediaTracksInformationCodecLevel,
  525. @(tracksInfo[i]->i_bitrate),
  526. VLCMediaTracksInformationBitrate,
  527. nil];
  528. if (tracksInfo[i]->psz_language)
  529. dictionary[VLCMediaTracksInformationLanguage] = [NSString stringWithUTF8String:tracksInfo[i]->psz_language];
  530. if (tracksInfo[i]->psz_description)
  531. dictionary[VLCMediaTracksInformationDescription] = [NSString stringWithUTF8String:tracksInfo[i]->psz_description];
  532. NSString *type;
  533. switch (tracksInfo[i]->i_type) {
  534. case libvlc_track_audio:
  535. type = VLCMediaTracksInformationTypeAudio;
  536. dictionary[VLCMediaTracksInformationAudioChannelsNumber] = @(tracksInfo[i]->audio->i_channels);
  537. dictionary[VLCMediaTracksInformationAudioRate] = @(tracksInfo[i]->audio->i_rate);
  538. break;
  539. case libvlc_track_video:
  540. type = VLCMediaTracksInformationTypeVideo;
  541. dictionary[VLCMediaTracksInformationVideoWidth] = @(tracksInfo[i]->video->i_width);
  542. dictionary[VLCMediaTracksInformationVideoHeight] = @(tracksInfo[i]->video->i_height);
  543. dictionary[VLCMediaTracksInformationSourceAspectRatio] = @(tracksInfo[i]->video->i_sar_num);
  544. dictionary[VLCMediaTracksInformationSourceAspectDenominator] = @(tracksInfo[i]->video->i_sar_den);
  545. dictionary[VLCMediaTracksInformationFrameRate] = @(tracksInfo[i]->video->i_frame_rate_num);
  546. dictionary[VLCMediaTracksInformationFrameRateDenominator] = @(tracksInfo[i]->video->i_frame_rate_den);
  547. break;
  548. case libvlc_track_text:
  549. type = VLCMediaTracksInformationTypeText;
  550. if (tracksInfo[i]->subtitle->psz_encoding)
  551. dictionary[VLCMediaTracksInformationTextEncoding] = [NSString stringWithUTF8String: tracksInfo[i]->subtitle->psz_encoding];
  552. break;
  553. case libvlc_track_unknown:
  554. default:
  555. type = VLCMediaTracksInformationTypeUnknown;
  556. break;
  557. }
  558. [dictionary setValue:type forKey:VLCMediaTracksInformationType];
  559. [array addObject:dictionary];
  560. }
  561. libvlc_media_tracks_release(tracksInfo, count);
  562. return array;
  563. }
  564. - (BOOL)isMediaSizeSuitableForDevice
  565. {
  566. #if TARGET_OS_IPHONE
  567. // Trigger parsing if needed
  568. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  569. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit) {
  570. [self parseWithOptions:VLCMediaParseLocal|VLCMediaParseNetwork];
  571. sleep(2);
  572. }
  573. NSUInteger biggestWidth = 0;
  574. NSUInteger biggestHeight = 0;
  575. libvlc_media_track_t **tracksInfo;
  576. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  577. for (NSUInteger i = 0; i < count; i++) {
  578. switch (tracksInfo[i]->i_type) {
  579. case libvlc_track_video:
  580. if (tracksInfo[i]->video->i_width > biggestWidth)
  581. biggestWidth = tracksInfo[i]->video->i_width;
  582. if (tracksInfo[i]->video->i_height > biggestHeight)
  583. biggestHeight = tracksInfo[i]->video->i_height;
  584. break;
  585. default:
  586. break;
  587. }
  588. }
  589. if (biggestHeight > 0 && biggestWidth > 0) {
  590. size_t size;
  591. sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  592. char *answer = malloc(size);
  593. sysctlbyname("hw.machine", answer, &size, NULL, 0);
  594. NSString *currentMachine = @(answer);
  595. free(answer);
  596. NSUInteger totalNumberOfPixels = biggestWidth * biggestHeight;
  597. if ([currentMachine hasPrefix:@"iPhone2"] || [currentMachine hasPrefix:@"iPhone3"] || [currentMachine hasPrefix:@"iPad1"] || [currentMachine hasPrefix:@"iPod3"] || [currentMachine hasPrefix:@"iPod4"]) {
  598. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  599. return (totalNumberOfPixels < 600000); // between 480p and 720p
  600. } 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"]) {
  601. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  602. return (totalNumberOfPixels < 922000); // 720p
  603. } else {
  604. // iPhone 5, iPad 4
  605. return (totalNumberOfPixels < 2074000); // 1080p
  606. }
  607. }
  608. #endif
  609. return YES;
  610. }
  611. - (NSString *)metadataForKey:(NSString *)key
  612. {
  613. if (!p_md)
  614. return nil;
  615. char *returnValue = libvlc_media_get_meta(p_md, [VLCMedia stringToMetaType:key]);
  616. if (!returnValue)
  617. return nil;
  618. NSString *actualReturnValue = @(returnValue);
  619. free(returnValue);
  620. return actualReturnValue;
  621. }
  622. - (void)setMetadata:(NSString *)data forKey:(NSString *)key
  623. {
  624. if (!p_md)
  625. return;
  626. libvlc_media_set_meta(p_md, [VLCMedia stringToMetaType:key], [data UTF8String]);
  627. }
  628. - (BOOL)saveMetadata
  629. {
  630. if (p_md)
  631. return libvlc_media_save_meta(p_md) != 0;
  632. return NO;
  633. }
  634. /******************************************************************************
  635. * Implementation VLCMedia ()
  636. */
  637. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  638. {
  639. static NSDictionary * stringToMetaDictionary = nil;
  640. // TODO: Thread safe-ize
  641. if (!stringToMetaDictionary) {
  642. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  643. stringToMetaDictionary =
  644. [NSDictionary dictionaryWithObjectsAndKeys:
  645. VLCStringToMeta(Title),
  646. VLCStringToMeta(Artist),
  647. VLCStringToMeta(Genre),
  648. VLCStringToMeta(Copyright),
  649. VLCStringToMeta(Album),
  650. VLCStringToMeta(TrackNumber),
  651. VLCStringToMeta(Description),
  652. VLCStringToMeta(Rating),
  653. VLCStringToMeta(Date),
  654. VLCStringToMeta(Setting),
  655. VLCStringToMeta(URL),
  656. VLCStringToMeta(Language),
  657. VLCStringToMeta(NowPlaying),
  658. VLCStringToMeta(Publisher),
  659. VLCStringToMeta(ArtworkURL),
  660. VLCStringToMeta(TrackID),
  661. VLCStringToMeta(TrackTotal),
  662. VLCStringToMeta(Director),
  663. VLCStringToMeta(Season),
  664. VLCStringToMeta(Episode),
  665. VLCStringToMeta(ShowName),
  666. VLCStringToMeta(Actors),
  667. VLCStringToMeta(AlbumArtist),
  668. VLCStringToMeta(DiscNumber),
  669. nil];
  670. #undef VLCStringToMeta
  671. }
  672. NSNumber * number = stringToMetaDictionary[string];
  673. return (libvlc_meta_t) (number ? [number intValue] : -1);
  674. }
  675. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  676. {
  677. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  678. VLCMetaToString(Title, type);
  679. VLCMetaToString(Artist, type);
  680. VLCMetaToString(Genre, type);
  681. VLCMetaToString(Copyright, type);
  682. VLCMetaToString(Album, type);
  683. VLCMetaToString(TrackNumber, type);
  684. VLCMetaToString(Description, type);
  685. VLCMetaToString(Rating, type);
  686. VLCMetaToString(Date, type);
  687. VLCMetaToString(Setting, type);
  688. VLCMetaToString(URL, type);
  689. VLCMetaToString(Language, type);
  690. VLCMetaToString(NowPlaying, type);
  691. VLCMetaToString(Publisher, type);
  692. VLCMetaToString(ArtworkURL, type);
  693. VLCMetaToString(TrackID, type);
  694. VLCMetaToString(TrackTotal, type);
  695. VLCMetaToString(Director, type);
  696. VLCMetaToString(Season, type);
  697. VLCMetaToString(Episode, type);
  698. VLCMetaToString(ShowName, type);
  699. VLCMetaToString(Actors, type);
  700. VLCMetaToString(AlbumArtist, type);
  701. VLCMetaToString(DiscNumber, type);
  702. #undef VLCMetaToString
  703. return nil;
  704. }
  705. - (void)initInternalMediaDescriptor
  706. {
  707. char * p_url = libvlc_media_get_mrl( p_md );
  708. if (!p_url)
  709. return;
  710. NSString *urlString = [NSString stringWithUTF8String:p_url];
  711. if (!urlString) {
  712. free(p_url);
  713. return;
  714. }
  715. urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  716. if (!urlString) {
  717. free(p_url);
  718. return;
  719. }
  720. _url = [NSURL URLWithString:urlString];
  721. if (!_url) /* Attempt to interpret as a file path then */ {
  722. _url = [NSURL fileURLWithPath:urlString];
  723. if(!_url) {
  724. free(p_url);
  725. return;
  726. }
  727. }
  728. free(p_url);
  729. libvlc_media_set_user_data(p_md, (__bridge void*)self);
  730. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md );
  731. if (p_em) {
  732. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, (__bridge void *)(self));
  733. libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, (__bridge void *)(self));
  734. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, (__bridge void *)(self));
  735. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, (__bridge void *)(self));
  736. libvlc_event_attach(p_em, libvlc_MediaParsedChanged, HandleMediaParsedChanged, (__bridge void *)(self));
  737. }
  738. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  739. if (p_mlist) {
  740. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  741. libvlc_media_list_release( p_mlist );
  742. }
  743. self.state = LibVLCStateToMediaState(libvlc_media_get_state( p_md ));
  744. }
  745. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  746. {
  747. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType] );
  748. NSString * newValue = psz_value ? @(psz_value) : nil;
  749. NSString * oldValue = [_metaDictionary valueForKey:metaType];
  750. free(psz_value);
  751. if (newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame)) {
  752. #if !TARGET_OS_IPHONE
  753. // Only fetch the art if needed. (ie, create the NSImage, if it was requested before)
  754. if (isArtFetched && [metaType isEqualToString:VLCMetaInformationArtworkURL]) {
  755. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  756. toTarget:self
  757. withObject:newValue];
  758. }
  759. #endif
  760. [_metaDictionary setValue:newValue forKeyPath:metaType];
  761. }
  762. }
  763. #if !TARGET_OS_IPHONE
  764. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  765. {
  766. @autoreleasepool {
  767. NSImage * art = nil;
  768. if (anURL) {
  769. // Go ahead and load up the art work
  770. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  771. // Don't attempt to fetch artwork from remote. Core will do that alone
  772. if ([artUrl isFileURL])
  773. art = [[NSImage alloc] initWithContentsOfURL:artUrl];
  774. }
  775. // If anything was found, lets save it to the meta data dictionary
  776. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  777. }
  778. }
  779. - (void)setArtwork:(NSImage *)art
  780. {
  781. if (!art)
  782. [(NSMutableDictionary *)_metaDictionary removeObjectForKey:@"artwork"];
  783. else
  784. ((NSMutableDictionary *)_metaDictionary)[@"artwork"] = art;
  785. }
  786. #endif
  787. - (void)parseIfNeeded
  788. {
  789. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  790. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit)
  791. [self parseWithOptions:VLCMediaParseLocal | VLCMediaFetchLocal];
  792. }
  793. - (void)metaChanged:(NSString *)metaType
  794. {
  795. [self fetchMetaInformationFromLibVLCWithType:metaType];
  796. if ([_delegate respondsToSelector:@selector(mediaMetaDataDidChange:)])
  797. [_delegate mediaMetaDataDidChange:self];
  798. }
  799. - (void)subItemAdded
  800. {
  801. if (_subitems)
  802. return; /* Nothing to do */
  803. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  804. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  805. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  806. libvlc_media_list_release( p_mlist );
  807. }
  808. - (void)parsedChanged:(NSNumber *)isParsedAsNumber
  809. {
  810. [self willChangeValueForKey:@"parsedStatus"];
  811. [self parsedStatus];
  812. [self didChangeValueForKey:@"parsedStatus"];
  813. if (!_delegate)
  814. return;
  815. if ([_delegate respondsToSelector:@selector(mediaDidFinishParsing:)])
  816. [_delegate mediaDidFinishParsing:self];
  817. }
  818. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  819. {
  820. [self setState: [newStateAsNumber intValue]];
  821. }
  822. #if TARGET_OS_IPHONE
  823. - (NSDictionary *)metaDictionary
  824. {
  825. if (!areOthersMetaFetched) {
  826. areOthersMetaFetched = YES;
  827. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  828. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtist];
  829. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationAlbum];
  830. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDate];
  831. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationGenre];
  832. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTrackNumber];
  833. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDiscNumber];
  834. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationNowPlaying];
  835. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationLanguage];
  836. }
  837. if (!isArtURLFetched) {
  838. isArtURLFetched = YES;
  839. /* Force isArtURLFetched, that will trigger artwork download eventually
  840. * And all the other meta will be added through the libvlc event system */
  841. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  842. }
  843. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  844. }
  845. #else
  846. - (NSDictionary *)metaDictionary
  847. {
  848. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  849. }
  850. - (id)valueForKeyPath:(NSString *)keyPath
  851. {
  852. if (!isArtFetched && [keyPath isEqualToString:@"metaDictionary.artwork"]) {
  853. isArtFetched = YES;
  854. /* Force the retrieval of the artwork now that someone asked for it */
  855. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  856. } else if (!areOthersMetaFetched && [keyPath hasPrefix:@"metaDictionary."]) {
  857. areOthersMetaFetched = YES;
  858. /* Force VLCMetaInformationTitle, that will trigger preparsing
  859. * And all the other meta will be added through the libvlc event system */
  860. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  861. } else if (!isArtURLFetched && [keyPath hasPrefix:@"metaDictionary.artworkURL"]) {
  862. isArtURLFetched = YES;
  863. /* Force isArtURLFetched, that will trigger artwork download eventually
  864. * And all the other meta will be added through the libvlc event system */
  865. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  866. }
  867. return [super valueForKeyPath:keyPath];
  868. }
  869. #endif
  870. @end
  871. /******************************************************************************
  872. * Implementation VLCMedia (LibVLCBridging)
  873. */
  874. @implementation VLCMedia (LibVLCBridging)
  875. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  876. {
  877. return [[VLCMedia alloc] initWithLibVLCMediaDescriptor:md];
  878. }
  879. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  880. {
  881. libvlc_media_t * p_md;
  882. p_md = libvlc_media_duplicate([media libVLCMediaDescriptor]);
  883. for (NSString * key in [options allKeys]) {
  884. if (options[key] != [NSNull null])
  885. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, options[key]] UTF8String]);
  886. else
  887. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@", key] UTF8String]);
  888. }
  889. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  890. }
  891. - (id)initWithLibVLCMediaDescriptor:(void *)md
  892. {
  893. if (self = [super init]) {
  894. libvlc_media_retain(md);
  895. p_md = md;
  896. _metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  897. [self initInternalMediaDescriptor];
  898. }
  899. return self;
  900. }
  901. - (void *)libVLCMediaDescriptor
  902. {
  903. return p_md;
  904. }
  905. @end