VLCMedia.m 33 KB

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