VLCMedia.m 32 KB

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