VLCMedia.m 38 KB

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