VLCMedia.m 37 KB

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