VLCMedia.m 32 KB

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