VLCMedia.m 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. * Soomin Lee <TheHungryBu # gmail.com>
  12. *
  13. * This program is free software; you can redistribute it and/or modify it
  14. * under the terms of the GNU Lesser General Public License as published by
  15. * the Free Software Foundation; either version 2.1 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Lesser General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Lesser General Public License
  24. * along with this program; if not, write to the Free Software Foundation,
  25. * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  26. *****************************************************************************/
  27. #import "VLCMedia.h"
  28. #import "VLCMediaList.h"
  29. #import "VLCEventManager.h"
  30. #import "VLCLibrary.h"
  31. #import "VLCLibVLCBridging.h"
  32. #import <vlc/libvlc.h>
  33. #import <sys/sysctl.h> // for sysctlbyname
  34. /* Meta Dictionary Keys */
  35. NSString *const VLCMetaInformationTitle = @"title";
  36. NSString *const VLCMetaInformationArtist = @"artist";
  37. NSString *const VLCMetaInformationGenre = @"genre";
  38. NSString *const VLCMetaInformationCopyright = @"copyright";
  39. NSString *const VLCMetaInformationAlbum = @"album";
  40. NSString *const VLCMetaInformationTrackNumber = @"trackNumber";
  41. NSString *const VLCMetaInformationDescription = @"description";
  42. NSString *const VLCMetaInformationRating = @"rating";
  43. NSString *const VLCMetaInformationDate = @"date";
  44. NSString *const VLCMetaInformationSetting = @"setting";
  45. NSString *const VLCMetaInformationURL = @"url";
  46. NSString *const VLCMetaInformationLanguage = @"language";
  47. NSString *const VLCMetaInformationNowPlaying = @"nowPlaying";
  48. NSString *const VLCMetaInformationPublisher = @"publisher";
  49. NSString *const VLCMetaInformationEncodedBy = @"encodedBy";
  50. NSString *const VLCMetaInformationArtworkURL = @"artworkURL";
  51. NSString *const VLCMetaInformationArtwork = @"artwork";
  52. NSString *const VLCMetaInformationTrackID = @"trackID";
  53. NSString *const VLCMetaInformationTrackTotal = @"trackTotal";
  54. NSString *const VLCMetaInformationDirector = @"director";
  55. NSString *const VLCMetaInformationSeason = @"season";
  56. NSString *const VLCMetaInformationEpisode = @"episode";
  57. NSString *const VLCMetaInformationShowName = @"showName";
  58. NSString *const VLCMetaInformationActors = @"actors";
  59. NSString *const VLCMetaInformationAlbumArtist = @"AlbumArtist";
  60. NSString *const VLCMetaInformationDiscNumber = @"discNumber";
  61. /* Notification Messages */
  62. NSString *const VLCMediaMetaChanged = @"VLCMediaMetaChanged";
  63. /******************************************************************************
  64. * VLCMedia ()
  65. */
  66. @interface VLCMedia()
  67. {
  68. void * p_md; ///< Internal media descriptor instance
  69. BOOL isArtFetched; ///< Value used to determine of the artwork has been parsed
  70. BOOL areOthersMetaFetched; ///< Value used to determine of the other meta has been parsed
  71. BOOL isArtURLFetched; ///< Value used to determine of the other meta has been preparsed
  72. NSMutableDictionary *_metaDictionary; ///< Dictionary to cache metadata read from libvlc
  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. libvlc_media_parsed_status_t status = libvlc_media_get_parsed_status(p_md);
  278. while (!_length && !(status == VLCMediaParsedStatusFailed || status == VLCMediaParsedStatusDone) && [aDate timeIntervalSinceNow] > 0) {
  279. usleep( thread_sleep );
  280. status = libvlc_media_get_parsed_status(p_md);
  281. }
  282. // So we're done waiting, but sometimes we trap the fact that the parsing
  283. // was done before the length gets assigned, so lets go ahead and assign
  284. // it ourselves.
  285. if (!_length)
  286. return [self length];
  287. }
  288. return _length;
  289. }
  290. - (BOOL)isParsed
  291. {
  292. VLCMediaParsedStatus status = [self parsedStatus];
  293. return (status == VLCMediaParsedStatusFailed || status == VLCMediaParsedStatusDone) ? YES:NO;
  294. }
  295. - (VLCMediaParsedStatus)parsedStatus
  296. {
  297. if (!p_md)
  298. return VLCMediaParsedStatusFailed;
  299. libvlc_media_parsed_status_t status = libvlc_media_get_parsed_status(p_md);
  300. return (VLCMediaParsedStatus)status;
  301. }
  302. - (void)parse
  303. {
  304. if (p_md)
  305. libvlc_media_parse_async(p_md);
  306. }
  307. - (void)synchronousParse
  308. {
  309. if (p_md)
  310. libvlc_media_parse(p_md);
  311. }
  312. - (int)parseWithOptions:(VLCMediaParsingOptions)options timeout:(int)timeoutValue
  313. {
  314. if (!p_md)
  315. return -1;
  316. // we are using the default time-out value
  317. return libvlc_media_parse_with_options(p_md,
  318. options,
  319. timeoutValue);
  320. }
  321. - (int)parseWithOptions:(VLCMediaParsingOptions)options
  322. {
  323. if (!p_md)
  324. return -1;
  325. // we are using the default time-out value
  326. return libvlc_media_parse_with_options(p_md,
  327. options,
  328. -1);
  329. }
  330. - (void)addOptions:(NSDictionary*)options
  331. {
  332. if (p_md) {
  333. [options enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
  334. if (![obj isKindOfClass:[NSNull class]])
  335. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, obj] UTF8String]);
  336. else
  337. libvlc_media_add_option(p_md, [key UTF8String]);
  338. }];
  339. }
  340. }
  341. - (int)storeCookie:(NSString * _Nonnull)cookie
  342. forHost:(NSString *_Nonnull)host
  343. path:(NSString *_Nonnull)path
  344. {
  345. if (!p_md || cookie == NULL || host == NULL || path == NULL) {
  346. return -1;
  347. }
  348. #if TARGET_OS_IPHONE
  349. return libvlc_media_cookie_jar_store(p_md,
  350. [cookie UTF8String],
  351. [host UTF8String],
  352. [path UTF8String]);
  353. #else
  354. return -1;
  355. #endif
  356. }
  357. - (void)clearStoredCookies
  358. {
  359. if (!p_md) {
  360. return;
  361. }
  362. #if TARGET_OS_IPHONE
  363. libvlc_media_cookie_jar_clear(p_md);
  364. #endif
  365. }
  366. - (NSDictionary *)stats
  367. {
  368. if (!p_md)
  369. return nil;
  370. libvlc_media_stats_t p_stats;
  371. libvlc_media_get_stats(p_md, &p_stats);
  372. return @{
  373. @"demuxBitrate" : @(p_stats.f_demux_bitrate),
  374. @"inputBitrate" : @(p_stats.f_input_bitrate),
  375. @"sendBitrate" : @(p_stats.f_send_bitrate),
  376. @"decodedAudio" : @(p_stats.i_decoded_audio),
  377. @"decodedVideo" : @(p_stats.i_decoded_video),
  378. @"demuxCorrupted" : @(p_stats.i_demux_corrupted),
  379. @"demuxDiscontinuity" : @(p_stats.i_demux_discontinuity),
  380. @"demuxReadBytes" : @(p_stats.i_demux_read_bytes),
  381. @"displayedPictures" : @(p_stats.i_displayed_pictures),
  382. @"lostAbuffers" : @(p_stats.i_lost_abuffers),
  383. @"lostPictures" : @(p_stats.i_lost_pictures),
  384. @"playedAbuffers" : @(p_stats.i_played_abuffers),
  385. @"readBytes" : @(p_stats.i_read_bytes),
  386. @"sentBytes" : @(p_stats.i_sent_bytes),
  387. @"sentPackets" : @(p_stats.i_sent_packets)
  388. };
  389. }
  390. - (NSInteger)numberOfReadBytesOnInput
  391. {
  392. if (!p_md)
  393. return 0;
  394. libvlc_media_stats_t p_stats;
  395. libvlc_media_get_stats(p_md, &p_stats);
  396. return p_stats.i_read_bytes;
  397. }
  398. - (float)inputBitrate
  399. {
  400. if (!p_md)
  401. return .0;
  402. libvlc_media_stats_t p_stats;
  403. libvlc_media_get_stats(p_md, &p_stats);
  404. return p_stats.f_input_bitrate;
  405. }
  406. - (NSInteger)numberOfReadBytesOnDemux
  407. {
  408. if (!p_md)
  409. return 0;
  410. libvlc_media_stats_t p_stats;
  411. libvlc_media_get_stats(p_md, &p_stats);
  412. return p_stats.i_demux_read_bytes;
  413. }
  414. - (float)demuxBitrate
  415. {
  416. if (!p_md)
  417. return .0;
  418. libvlc_media_stats_t p_stats;
  419. libvlc_media_get_stats(p_md, &p_stats);
  420. return p_stats.f_demux_bitrate;
  421. }
  422. - (NSInteger)numberOfDecodedVideoBlocks
  423. {
  424. if (!p_md)
  425. return 0;
  426. libvlc_media_stats_t p_stats;
  427. libvlc_media_get_stats(p_md, &p_stats);
  428. return p_stats.i_decoded_video;
  429. }
  430. - (NSInteger)numberOfDecodedAudioBlocks
  431. {
  432. if (!p_md)
  433. return 0;
  434. libvlc_media_stats_t p_stats;
  435. libvlc_media_get_stats(p_md, &p_stats);
  436. return p_stats.i_decoded_audio;
  437. }
  438. - (NSInteger)numberOfDisplayedPictures
  439. {
  440. if (!p_md)
  441. return 0;
  442. libvlc_media_stats_t p_stats;
  443. libvlc_media_get_stats(p_md, &p_stats);
  444. return p_stats.i_displayed_pictures;
  445. }
  446. - (NSInteger)numberOfLostPictures
  447. {
  448. if (!p_md)
  449. return 0;
  450. libvlc_media_stats_t p_stats;
  451. libvlc_media_get_stats(p_md, &p_stats);
  452. return p_stats.i_lost_pictures;
  453. }
  454. - (NSInteger)numberOfPlayedAudioBuffers
  455. {
  456. if (!p_md)
  457. return 0;
  458. libvlc_media_stats_t p_stats;
  459. libvlc_media_get_stats(p_md, &p_stats);
  460. return p_stats.i_played_abuffers;
  461. }
  462. - (NSInteger)numberOfLostAudioBuffers
  463. {
  464. if (!p_md)
  465. return 0;
  466. libvlc_media_stats_t p_stats;
  467. libvlc_media_get_stats(p_md, &p_stats);
  468. return p_stats.i_lost_abuffers;
  469. }
  470. - (NSInteger)numberOfSentPackets
  471. {
  472. if (!p_md)
  473. return 0;
  474. libvlc_media_stats_t p_stats;
  475. libvlc_media_get_stats(p_md, &p_stats);
  476. return p_stats.i_sent_packets;
  477. }
  478. - (NSInteger)numberOfSentBytes
  479. {
  480. if (!p_md)
  481. return 0;
  482. libvlc_media_stats_t p_stats;
  483. libvlc_media_get_stats(p_md, &p_stats);
  484. return p_stats.i_sent_bytes;
  485. }
  486. - (float)streamOutputBitrate
  487. {
  488. if (!p_md)
  489. return .0;
  490. libvlc_media_stats_t p_stats;
  491. libvlc_media_get_stats(p_md, &p_stats);
  492. return p_stats.f_send_bitrate;
  493. }
  494. - (NSInteger)numberOfCorruptedDataPackets
  495. {
  496. if (!p_md)
  497. return 0;
  498. libvlc_media_stats_t p_stats;
  499. libvlc_media_get_stats(p_md, &p_stats);
  500. return p_stats.i_demux_corrupted;
  501. }
  502. - (NSInteger)numberOfDiscontinuties
  503. {
  504. if (!p_md)
  505. return 0;
  506. libvlc_media_stats_t p_stats;
  507. libvlc_media_get_stats(p_md, &p_stats);
  508. return p_stats.i_demux_discontinuity;
  509. }
  510. NSString *const VLCMediaTracksInformationCodec = @"codec"; // NSNumber
  511. NSString *const VLCMediaTracksInformationId = @"id"; // NSNumber
  512. NSString *const VLCMediaTracksInformationType = @"type"; // NSString
  513. NSString *const VLCMediaTracksInformationCodecProfile = @"profile"; // NSNumber
  514. NSString *const VLCMediaTracksInformationCodecLevel = @"level"; // NSNumber
  515. NSString *const VLCMediaTracksInformationTypeAudio = @"audio";
  516. NSString *const VLCMediaTracksInformationTypeVideo = @"video";
  517. NSString *const VLCMediaTracksInformationTypeText = @"text";
  518. NSString *const VLCMediaTracksInformationTypeUnknown = @"unknown";
  519. NSString *const VLCMediaTracksInformationBitrate = @"bitrate"; // NSNumber
  520. NSString *const VLCMediaTracksInformationLanguage = @"language"; // NSString
  521. NSString *const VLCMediaTracksInformationDescription = @"description"; // NSString
  522. NSString *const VLCMediaTracksInformationAudioChannelsNumber = @"channelsNumber"; // NSNumber
  523. NSString *const VLCMediaTracksInformationAudioRate = @"rate"; // NSNumber
  524. NSString *const VLCMediaTracksInformationVideoHeight = @"height"; // NSNumber
  525. NSString *const VLCMediaTracksInformationVideoWidth = @"width"; // NSNumber
  526. NSString *const VLCMediaTracksInformationVideoOrientation = @"orientation"; // NSNumber
  527. NSString *const VLCMediaTracksInformationVideoProjection = @"projection"; // NSNumber
  528. NSString *const VLCMediaTracksInformationSourceAspectRatio = @"sar_num"; // NSNumber
  529. NSString *const VLCMediaTracksInformationSourceAspectDenominator = @"sar_den"; // NSNumber
  530. NSString *const VLCMediaTracksInformationFrameRate = @"frame_rate_num"; // NSNumber
  531. NSString *const VLCMediaTracksInformationFrameRateDenominator = @"frame_rate_den"; // NSNumber
  532. NSString *const VLCMediaTracksInformationTextEncoding = @"encoding"; // NSString
  533. - (NSArray *)tracksInformation
  534. {
  535. libvlc_media_track_t **tracksInfo;
  536. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  537. NSMutableArray *array = [NSMutableArray array];
  538. for (NSUInteger i = 0; i < count; i++) {
  539. NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  540. @(tracksInfo[i]->i_codec),
  541. VLCMediaTracksInformationCodec,
  542. @(tracksInfo[i]->i_id),
  543. VLCMediaTracksInformationId,
  544. @(tracksInfo[i]->i_profile),
  545. VLCMediaTracksInformationCodecProfile,
  546. @(tracksInfo[i]->i_level),
  547. VLCMediaTracksInformationCodecLevel,
  548. @(tracksInfo[i]->i_bitrate),
  549. VLCMediaTracksInformationBitrate,
  550. nil];
  551. if (tracksInfo[i]->psz_language)
  552. dictionary[VLCMediaTracksInformationLanguage] = [NSString stringWithUTF8String:tracksInfo[i]->psz_language];
  553. if (tracksInfo[i]->psz_description)
  554. dictionary[VLCMediaTracksInformationDescription] = [NSString stringWithUTF8String:tracksInfo[i]->psz_description];
  555. NSString *type;
  556. switch (tracksInfo[i]->i_type) {
  557. case libvlc_track_audio:
  558. type = VLCMediaTracksInformationTypeAudio;
  559. dictionary[VLCMediaTracksInformationAudioChannelsNumber] = @(tracksInfo[i]->audio->i_channels);
  560. dictionary[VLCMediaTracksInformationAudioRate] = @(tracksInfo[i]->audio->i_rate);
  561. break;
  562. case libvlc_track_video:
  563. type = VLCMediaTracksInformationTypeVideo;
  564. dictionary[VLCMediaTracksInformationVideoWidth] = @(tracksInfo[i]->video->i_width);
  565. dictionary[VLCMediaTracksInformationVideoHeight] = @(tracksInfo[i]->video->i_height);
  566. dictionary[VLCMediaTracksInformationVideoOrientation] = @(tracksInfo[i]->video->i_orientation);
  567. dictionary[VLCMediaTracksInformationVideoProjection] = @(tracksInfo[i]->video->i_projection);
  568. dictionary[VLCMediaTracksInformationSourceAspectRatio] = @(tracksInfo[i]->video->i_sar_num);
  569. dictionary[VLCMediaTracksInformationSourceAspectDenominator] = @(tracksInfo[i]->video->i_sar_den);
  570. dictionary[VLCMediaTracksInformationFrameRate] = @(tracksInfo[i]->video->i_frame_rate_num);
  571. dictionary[VLCMediaTracksInformationFrameRateDenominator] = @(tracksInfo[i]->video->i_frame_rate_den);
  572. break;
  573. case libvlc_track_text:
  574. type = VLCMediaTracksInformationTypeText;
  575. if (tracksInfo[i]->subtitle->psz_encoding)
  576. dictionary[VLCMediaTracksInformationTextEncoding] = [NSString stringWithUTF8String: tracksInfo[i]->subtitle->psz_encoding];
  577. break;
  578. case libvlc_track_unknown:
  579. default:
  580. type = VLCMediaTracksInformationTypeUnknown;
  581. break;
  582. }
  583. [dictionary setValue:type forKey:VLCMediaTracksInformationType];
  584. [array addObject:dictionary];
  585. }
  586. libvlc_media_tracks_release(tracksInfo, count);
  587. return array;
  588. }
  589. - (BOOL)isMediaSizeSuitableForDevice
  590. {
  591. #if TARGET_OS_IPHONE
  592. // Trigger parsing if needed
  593. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  594. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit) {
  595. [self parseWithOptions:VLCMediaParseLocal|VLCMediaParseNetwork];
  596. sleep(2);
  597. }
  598. NSUInteger biggestWidth = 0;
  599. NSUInteger biggestHeight = 0;
  600. libvlc_media_track_t **tracksInfo;
  601. unsigned int count = libvlc_media_tracks_get(p_md, &tracksInfo);
  602. for (NSUInteger i = 0; i < count; i++) {
  603. switch (tracksInfo[i]->i_type) {
  604. case libvlc_track_video:
  605. if (tracksInfo[i]->video->i_width > biggestWidth)
  606. biggestWidth = tracksInfo[i]->video->i_width;
  607. if (tracksInfo[i]->video->i_height > biggestHeight)
  608. biggestHeight = tracksInfo[i]->video->i_height;
  609. break;
  610. default:
  611. break;
  612. }
  613. }
  614. if (biggestHeight > 0 && biggestWidth > 0) {
  615. size_t size;
  616. sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  617. char *answer = malloc(size);
  618. sysctlbyname("hw.machine", answer, &size, NULL, 0);
  619. NSString *currentMachine = @(answer);
  620. free(answer);
  621. NSUInteger totalNumberOfPixels = biggestWidth * biggestHeight;
  622. if ([currentMachine hasPrefix:@"iPhone2"] || [currentMachine hasPrefix:@"iPhone3"] || [currentMachine hasPrefix:@"iPad1"] || [currentMachine hasPrefix:@"iPod3"] || [currentMachine hasPrefix:@"iPod4"]) {
  623. // iPhone 3GS, iPhone 4, first gen. iPad, 3rd and 4th generation iPod touch
  624. return (totalNumberOfPixels < 600000); // between 480p and 720p
  625. } 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"]) {
  626. // iPhone 4S, iPad 2 and 3, iPod 4 and 5
  627. return (totalNumberOfPixels < 922000); // 720p
  628. } else {
  629. // iPhone 5, iPad 4
  630. return (totalNumberOfPixels < 2074000); // 1080p
  631. }
  632. }
  633. #endif
  634. return YES;
  635. }
  636. - (NSString *)metadataForKey:(NSString *)key
  637. {
  638. if (!p_md)
  639. return nil;
  640. char *returnValue = libvlc_media_get_meta(p_md, [VLCMedia stringToMetaType:key]);
  641. if (!returnValue)
  642. return nil;
  643. NSString *actualReturnValue = @(returnValue);
  644. free(returnValue);
  645. return actualReturnValue;
  646. }
  647. - (void)setMetadata:(NSString *)data forKey:(NSString *)key
  648. {
  649. if (!p_md)
  650. return;
  651. libvlc_media_set_meta(p_md, [VLCMedia stringToMetaType:key], [data UTF8String]);
  652. }
  653. - (BOOL)saveMetadata
  654. {
  655. if (p_md)
  656. return libvlc_media_save_meta(p_md) != 0;
  657. return NO;
  658. }
  659. /******************************************************************************
  660. * Implementation VLCMedia ()
  661. */
  662. + (libvlc_meta_t)stringToMetaType:(NSString *)string
  663. {
  664. static NSDictionary * stringToMetaDictionary = nil;
  665. // TODO: Thread safe-ize
  666. if (!stringToMetaDictionary) {
  667. #define VLCStringToMeta( name ) [NSNumber numberWithInt: libvlc_meta_##name], VLCMetaInformation##name
  668. stringToMetaDictionary =
  669. [NSDictionary dictionaryWithObjectsAndKeys:
  670. VLCStringToMeta(Title),
  671. VLCStringToMeta(Artist),
  672. VLCStringToMeta(Genre),
  673. VLCStringToMeta(Copyright),
  674. VLCStringToMeta(Album),
  675. VLCStringToMeta(TrackNumber),
  676. VLCStringToMeta(Description),
  677. VLCStringToMeta(Rating),
  678. VLCStringToMeta(Date),
  679. VLCStringToMeta(Setting),
  680. VLCStringToMeta(URL),
  681. VLCStringToMeta(Language),
  682. VLCStringToMeta(NowPlaying),
  683. VLCStringToMeta(Publisher),
  684. VLCStringToMeta(ArtworkURL),
  685. VLCStringToMeta(TrackID),
  686. VLCStringToMeta(TrackTotal),
  687. VLCStringToMeta(Director),
  688. VLCStringToMeta(Season),
  689. VLCStringToMeta(Episode),
  690. VLCStringToMeta(ShowName),
  691. VLCStringToMeta(Actors),
  692. VLCStringToMeta(AlbumArtist),
  693. VLCStringToMeta(DiscNumber),
  694. nil];
  695. #undef VLCStringToMeta
  696. }
  697. NSNumber * number = stringToMetaDictionary[string];
  698. return (libvlc_meta_t) (number ? [number intValue] : -1);
  699. }
  700. + (NSString *)metaTypeToString:(libvlc_meta_t)type
  701. {
  702. #define VLCMetaToString( name, type ) if (libvlc_meta_##name == type) return VLCMetaInformation##name;
  703. VLCMetaToString(Title, type);
  704. VLCMetaToString(Artist, type);
  705. VLCMetaToString(Genre, type);
  706. VLCMetaToString(Copyright, type);
  707. VLCMetaToString(Album, type);
  708. VLCMetaToString(TrackNumber, type);
  709. VLCMetaToString(Description, type);
  710. VLCMetaToString(Rating, type);
  711. VLCMetaToString(Date, type);
  712. VLCMetaToString(Setting, type);
  713. VLCMetaToString(URL, type);
  714. VLCMetaToString(Language, type);
  715. VLCMetaToString(NowPlaying, type);
  716. VLCMetaToString(Publisher, type);
  717. VLCMetaToString(ArtworkURL, type);
  718. VLCMetaToString(TrackID, type);
  719. VLCMetaToString(TrackTotal, type);
  720. VLCMetaToString(Director, type);
  721. VLCMetaToString(Season, type);
  722. VLCMetaToString(Episode, type);
  723. VLCMetaToString(ShowName, type);
  724. VLCMetaToString(Actors, type);
  725. VLCMetaToString(AlbumArtist, type);
  726. VLCMetaToString(DiscNumber, type);
  727. #undef VLCMetaToString
  728. return nil;
  729. }
  730. - (void)initInternalMediaDescriptor
  731. {
  732. char * p_url = libvlc_media_get_mrl( p_md );
  733. if (!p_url)
  734. return;
  735. NSString *urlString = [NSString stringWithUTF8String:p_url];
  736. if (!urlString) {
  737. free(p_url);
  738. return;
  739. }
  740. urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  741. if (!urlString) {
  742. free(p_url);
  743. return;
  744. }
  745. _url = [NSURL URLWithString:urlString];
  746. if (!_url) /* Attempt to interpret as a file path then */ {
  747. _url = [NSURL fileURLWithPath:urlString];
  748. if(!_url) {
  749. free(p_url);
  750. return;
  751. }
  752. }
  753. free(p_url);
  754. libvlc_media_set_user_data(p_md, (__bridge void*)self);
  755. libvlc_event_manager_t * p_em = libvlc_media_event_manager( p_md );
  756. if (p_em) {
  757. libvlc_event_attach(p_em, libvlc_MediaMetaChanged, HandleMediaMetaChanged, (__bridge void *)(self));
  758. libvlc_event_attach(p_em, libvlc_MediaDurationChanged, HandleMediaDurationChanged, (__bridge void *)(self));
  759. libvlc_event_attach(p_em, libvlc_MediaStateChanged, HandleMediaStateChanged, (__bridge void *)(self));
  760. libvlc_event_attach(p_em, libvlc_MediaSubItemAdded, HandleMediaSubItemAdded, (__bridge void *)(self));
  761. libvlc_event_attach(p_em, libvlc_MediaParsedChanged, HandleMediaParsedChanged, (__bridge void *)(self));
  762. }
  763. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  764. if (p_mlist) {
  765. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  766. libvlc_media_list_release( p_mlist );
  767. }
  768. self.state = LibVLCStateToMediaState(libvlc_media_get_state( p_md ));
  769. }
  770. - (void)fetchMetaInformationFromLibVLCWithType:(NSString *)metaType
  771. {
  772. char * psz_value = libvlc_media_get_meta( p_md, [VLCMedia stringToMetaType:metaType] );
  773. NSString * newValue = psz_value ? @(psz_value) : nil;
  774. NSString * oldValue = [_metaDictionary valueForKey:metaType];
  775. free(psz_value);
  776. if (newValue != oldValue && !(oldValue && newValue && [oldValue compare:newValue] == NSOrderedSame)) {
  777. #if !TARGET_OS_IPHONE
  778. // Only fetch the art if needed. (ie, create the NSImage, if it was requested before)
  779. if (isArtFetched && [metaType isEqualToString:VLCMetaInformationArtworkURL]) {
  780. [NSThread detachNewThreadSelector:@selector(fetchMetaInformationForArtWorkWithURL:)
  781. toTarget:self
  782. withObject:newValue];
  783. }
  784. #endif
  785. [_metaDictionary setValue:newValue forKeyPath:metaType];
  786. }
  787. }
  788. #if !TARGET_OS_IPHONE
  789. - (void)fetchMetaInformationForArtWorkWithURL:(NSString *)anURL
  790. {
  791. @autoreleasepool {
  792. NSImage * art = nil;
  793. if (anURL) {
  794. // Go ahead and load up the art work
  795. NSURL * artUrl = [NSURL URLWithString:[anURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  796. // Don't attempt to fetch artwork from remote. Core will do that alone
  797. if ([artUrl isFileURL])
  798. art = [[NSImage alloc] initWithContentsOfURL:artUrl];
  799. }
  800. // If anything was found, lets save it to the meta data dictionary
  801. [self performSelectorOnMainThread:@selector(setArtwork:) withObject:art waitUntilDone:NO];
  802. }
  803. }
  804. - (void)setArtwork:(NSImage *)art
  805. {
  806. if (!art)
  807. [(NSMutableDictionary *)_metaDictionary removeObjectForKey:@"artwork"];
  808. else
  809. ((NSMutableDictionary *)_metaDictionary)[@"artwork"] = art;
  810. }
  811. #endif
  812. - (void)parseIfNeeded
  813. {
  814. VLCMediaParsedStatus parsedStatus = [self parsedStatus];
  815. if (parsedStatus == VLCMediaParsedStatusSkipped || parsedStatus == VLCMediaParsedStatusInit)
  816. [self parseWithOptions:VLCMediaParseLocal | VLCMediaFetchLocal];
  817. }
  818. - (void)metaChanged:(NSString *)metaType
  819. {
  820. [self fetchMetaInformationFromLibVLCWithType:metaType];
  821. if ([_delegate respondsToSelector:@selector(mediaMetaDataDidChange:)])
  822. [_delegate mediaMetaDataDidChange:self];
  823. }
  824. - (void)subItemAdded
  825. {
  826. if (_subitems)
  827. return; /* Nothing to do */
  828. libvlc_media_list_t * p_mlist = libvlc_media_subitems( p_md );
  829. NSAssert( p_mlist, @"The mlist shouldn't be nil, we are receiving a subItemAdded");
  830. self.subitems = [VLCMediaList mediaListWithLibVLCMediaList:p_mlist];
  831. libvlc_media_list_release( p_mlist );
  832. }
  833. - (void)parsedChanged:(NSNumber *)isParsedAsNumber
  834. {
  835. [self willChangeValueForKey:@"parsedStatus"];
  836. [self parsedStatus];
  837. [self didChangeValueForKey:@"parsedStatus"];
  838. if (!_delegate)
  839. return;
  840. if ([_delegate respondsToSelector:@selector(mediaDidFinishParsing:)])
  841. [_delegate mediaDidFinishParsing:self];
  842. }
  843. - (void)setStateAsNumber:(NSNumber *)newStateAsNumber
  844. {
  845. [self setState: [newStateAsNumber intValue]];
  846. }
  847. #if TARGET_OS_IPHONE
  848. - (NSDictionary *)metaDictionary
  849. {
  850. if (!areOthersMetaFetched) {
  851. areOthersMetaFetched = YES;
  852. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  853. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtist];
  854. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationAlbum];
  855. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDate];
  856. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationGenre];
  857. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTrackNumber];
  858. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationDiscNumber];
  859. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationNowPlaying];
  860. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationLanguage];
  861. }
  862. if (!isArtURLFetched) {
  863. isArtURLFetched = YES;
  864. /* Force isArtURLFetched, that will trigger artwork download eventually
  865. * And all the other meta will be added through the libvlc event system */
  866. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  867. }
  868. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  869. }
  870. #else
  871. - (NSDictionary *)metaDictionary
  872. {
  873. return [NSDictionary dictionaryWithDictionary:_metaDictionary];
  874. }
  875. - (id)valueForKeyPath:(NSString *)keyPath
  876. {
  877. if (!isArtFetched && [keyPath isEqualToString:@"metaDictionary.artwork"]) {
  878. isArtFetched = YES;
  879. /* Force the retrieval of the artwork now that someone asked for it */
  880. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  881. } else if (!areOthersMetaFetched && [keyPath hasPrefix:@"metaDictionary."]) {
  882. areOthersMetaFetched = YES;
  883. /* Force VLCMetaInformationTitle, that will trigger preparsing
  884. * And all the other meta will be added through the libvlc event system */
  885. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationTitle];
  886. } else if (!isArtURLFetched && [keyPath hasPrefix:@"metaDictionary.artworkURL"]) {
  887. isArtURLFetched = YES;
  888. /* Force isArtURLFetched, that will trigger artwork download eventually
  889. * And all the other meta will be added through the libvlc event system */
  890. [self fetchMetaInformationFromLibVLCWithType: VLCMetaInformationArtworkURL];
  891. }
  892. return [super valueForKeyPath:keyPath];
  893. }
  894. #endif
  895. @end
  896. /******************************************************************************
  897. * Implementation VLCMedia (LibVLCBridging)
  898. */
  899. @implementation VLCMedia (LibVLCBridging)
  900. + (id)mediaWithLibVLCMediaDescriptor:(void *)md
  901. {
  902. return [[VLCMedia alloc] initWithLibVLCMediaDescriptor:md];
  903. }
  904. + (id)mediaWithMedia:(VLCMedia *)media andLibVLCOptions:(NSDictionary *)options
  905. {
  906. libvlc_media_t * p_md;
  907. p_md = libvlc_media_duplicate([media libVLCMediaDescriptor]);
  908. for (NSString * key in [options allKeys]) {
  909. if (options[key] != [NSNull null])
  910. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@=%@", key, options[key]] UTF8String]);
  911. else
  912. libvlc_media_add_option(p_md, [[NSString stringWithFormat:@"%@", key] UTF8String]);
  913. }
  914. return [VLCMedia mediaWithLibVLCMediaDescriptor:p_md];
  915. }
  916. - (id)initWithLibVLCMediaDescriptor:(void *)md
  917. {
  918. if (self = [super init]) {
  919. libvlc_media_retain(md);
  920. p_md = md;
  921. _metaDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
  922. [self initInternalMediaDescriptor];
  923. }
  924. return self;
  925. }
  926. - (void *)libVLCMediaDescriptor
  927. {
  928. return p_md;
  929. }
  930. @end