VLCMedia.m 37 KB

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