VLCMedia.m 35 KB

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