VLCMedia.m 32 KB

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