VLCMediaThumbnailer.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /*****************************************************************************
  2. * VLCKit: VLCMediaThumbnailer
  3. *****************************************************************************
  4. * Copyright (C) 2010-2012 Pierre d'Herbemont and VideoLAN
  5. *
  6. * Authors: Pierre d'Herbemont
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU Lesser General Public License as published by
  10. * the Free Software Foundation; either version 2.1 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public License
  19. * along with this program; if not, write to the Free Software Foundation,
  20. * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  21. *****************************************************************************/
  22. #import <vlc/vlc.h>
  23. #import "VLCMediaThumbnailer.h"
  24. #import "VLCLibVLCBridging.h"
  25. @interface VLCMediaThumbnailer ()
  26. {
  27. id<VLCMediaThumbnailerDelegate> __weak _delegate;
  28. VLCMedia *_media;
  29. void *_mp;
  30. CGImageRef _thumbnail;
  31. void *_data;
  32. NSTimer *_parsingTimeoutTimer;
  33. NSTimer *_thumbnailingTimeoutTimer;
  34. CGFloat _thumbnailHeight,_thumbnailWidth;
  35. float _snapshotPosition;
  36. CGFloat _effectiveThumbnailHeight,_effectiveThumbnailWidth;
  37. int _numberOfReceivedFrames;
  38. BOOL _shouldRejectFrames;
  39. void * _internalLibVLCInstance;
  40. }
  41. - (void)didFetchThumbnail;
  42. - (void)notifyDelegate;
  43. - (void)fetchThumbnail;
  44. - (void)startFetchingThumbnail;
  45. @property (readonly, assign, nonatomic) void *dataPointer;
  46. @property (readonly, assign, nonatomic) BOOL shouldRejectFrames;
  47. @end
  48. static void *lock(void *opaque, void **pixels)
  49. {
  50. VLCMediaThumbnailer *thumbnailer = (__bridge VLCMediaThumbnailer *)(opaque);
  51. *pixels = [thumbnailer dataPointer];
  52. assert(*pixels);
  53. return NULL;
  54. }
  55. static const size_t kDefaultImageWidth = 320;
  56. static const size_t kDefaultImageHeight = 240;
  57. static const float kSnapshotPosition = 0.3;
  58. static const long long kStandardStartTime = 150000;
  59. void unlock(void *opaque, void *picture, void *const *p_pixels)
  60. {
  61. VLCMediaThumbnailer *thumbnailer = (__bridge VLCMediaThumbnailer *)(opaque);
  62. assert(!picture);
  63. assert([thumbnailer dataPointer] == *p_pixels);
  64. // We may already have a thumbnail if we are receiving picture after the first one.
  65. // Just ignore.
  66. if ([thumbnailer thumbnail] || [thumbnailer shouldRejectFrames])
  67. return;
  68. [thumbnailer performSelectorOnMainThread:@selector(didFetchThumbnail) withObject:nil waitUntilDone:YES];
  69. }
  70. @implementation VLCMediaThumbnailer
  71. @synthesize media=_media;
  72. @synthesize delegate=_delegate;
  73. @synthesize thumbnail=_thumbnail;
  74. @synthesize dataPointer=_data;
  75. @synthesize thumbnailWidth=_thumbnailWidth;
  76. @synthesize thumbnailHeight=_thumbnailHeight;
  77. @synthesize snapshotPosition=_snapshotPosition;
  78. @synthesize shouldRejectFrames=_shouldRejectFrames;
  79. + (VLCMediaThumbnailer *)thumbnailerWithMedia:(VLCMedia *)media andDelegate:(id<VLCMediaThumbnailerDelegate>)delegate
  80. {
  81. id obj = [[[self class] alloc] init];
  82. [obj setMedia:media];
  83. [obj setDelegate:delegate];
  84. [obj setLibVLCinstance:[VLCLibrary sharedInstance]];
  85. return obj;
  86. }
  87. + (VLCMediaThumbnailer *)thumbnailerWithMedia:(VLCMedia *)media delegate:(id<VLCMediaThumbnailerDelegate>)delegate andVLCLibrary:(VLCLibrary *)library
  88. {
  89. id obj = [[[self class] alloc] init];
  90. [obj setMedia:media];
  91. [obj setDelegate:delegate];
  92. if (library)
  93. [obj setLibVLCinstance:library.instance];
  94. else
  95. [obj setLibVLCinstance:[VLCLibrary sharedInstance]];
  96. return obj;
  97. }
  98. - (void)dealloc
  99. {
  100. NSAssert(!_thumbnailingTimeoutTimer, @"Timer not released");
  101. NSAssert(!_parsingTimeoutTimer, @"Timer not released");
  102. NSAssert(!_data, @"Data not released");
  103. NSAssert(!_mp, @"Not properly retained");
  104. if (_thumbnail)
  105. CGImageRelease(_thumbnail);
  106. if (_internalLibVLCInstance)
  107. libvlc_release(_internalLibVLCInstance);
  108. }
  109. - (void)setLibVLCinstance:(void *)libVLCinstance
  110. {
  111. _internalLibVLCInstance = libVLCinstance;
  112. libvlc_retain(_internalLibVLCInstance);
  113. }
  114. - (void *)libVLCinstance
  115. {
  116. return _internalLibVLCInstance;
  117. }
  118. - (void)fetchThumbnail
  119. {
  120. NSAssert(!_data, @"We are already fetching a thumbnail");
  121. if (![_media isParsed]) {
  122. [_media addObserver:self forKeyPath:@"parsed" options:0 context:NULL];
  123. [_media synchronousParse];
  124. NSAssert(!_parsingTimeoutTimer, @"We already have a timer around");
  125. _parsingTimeoutTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(mediaParsingTimedOut) userInfo:nil repeats:NO];
  126. return;
  127. }
  128. [self startFetchingThumbnail];
  129. }
  130. - (void)startFetchingThumbnail
  131. {
  132. NSArray *tracks = [_media tracksInformation];
  133. // Find the video track
  134. NSDictionary *videoTrack = nil;
  135. for (NSDictionary *track in tracks) {
  136. NSString *type = track[VLCMediaTracksInformationType];
  137. if ([type isEqualToString:VLCMediaTracksInformationTypeVideo]) {
  138. videoTrack = track;
  139. break;
  140. }
  141. }
  142. unsigned imageWidth = _thumbnailWidth > 0 ? _thumbnailWidth : kDefaultImageWidth;
  143. unsigned imageHeight = _thumbnailHeight > 0 ? _thumbnailHeight : kDefaultImageHeight;
  144. float snapshotPosition = _snapshotPosition > 0 ? _snapshotPosition : kSnapshotPosition;
  145. if (!videoTrack) {
  146. VKLog(@"WARNING: Can't find video track info, skipping file");
  147. [_parsingTimeoutTimer invalidate];
  148. _parsingTimeoutTimer = nil;
  149. [self mediaThumbnailingTimedOut];
  150. return;
  151. } else {
  152. int videoHeight = [videoTrack[VLCMediaTracksInformationVideoHeight] intValue];
  153. int videoWidth = [videoTrack[VLCMediaTracksInformationVideoWidth] intValue];
  154. // Constraining to the aspect ratio of the video.
  155. double ratio;
  156. if ((double)imageWidth / imageHeight < (double)videoWidth / videoHeight)
  157. ratio = (double)imageHeight / videoHeight;
  158. else
  159. ratio = (double)imageWidth / videoWidth;
  160. int newWidth = round(videoWidth * ratio);
  161. int newHeight = round(videoHeight * ratio);
  162. imageWidth = newWidth > 0 ? newWidth : imageWidth;
  163. imageHeight = newHeight > 0 ? newHeight : imageHeight;
  164. }
  165. _numberOfReceivedFrames = 0;
  166. NSAssert(!_shouldRejectFrames, @"Are we still running?");
  167. _effectiveThumbnailHeight = imageHeight;
  168. _effectiveThumbnailWidth = imageWidth;
  169. _data = calloc(1, imageWidth * imageHeight * 4);
  170. NSAssert(_data, @"Can't create data");
  171. NSAssert(!_mp, @"We are already fetching a thumbnail");
  172. _mp = libvlc_media_player_new(self.libVLCinstance);
  173. libvlc_media_add_option([_media libVLCMediaDescriptor], "no-audio");
  174. libvlc_media_add_option([_media libVLCMediaDescriptor], "no-videotoolbox-zero-copy");
  175. libvlc_media_player_set_media(_mp, [_media libVLCMediaDescriptor]);
  176. libvlc_video_set_format(_mp, "RGBA", imageWidth, imageHeight, 4 * imageWidth);
  177. libvlc_video_set_callbacks(_mp, lock, unlock, NULL, (__bridge void *)(self));
  178. if (snapshotPosition == kSnapshotPosition) {
  179. int length = _media.length.intValue;
  180. if (length < kStandardStartTime) {
  181. VKLog(@"short file detected");
  182. if (length > 1000) {
  183. VKLog(@"attempting seek to %is", (length * 25 / 100000));
  184. libvlc_media_add_option([_media libVLCMediaDescriptor], [[NSString stringWithFormat:@"start-time=%i", (length * 25 / 100000)] UTF8String]);
  185. }
  186. } else
  187. libvlc_media_add_option([_media libVLCMediaDescriptor], [[NSString stringWithFormat:@"start-time=%lli", (kStandardStartTime / 1000)] UTF8String]);
  188. }
  189. libvlc_media_player_play(_mp);
  190. NSAssert(!_thumbnailingTimeoutTimer, @"We already have a timer around");
  191. _thumbnailingTimeoutTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(mediaThumbnailingTimedOut) userInfo:nil repeats:NO];
  192. }
  193. - (void)mediaParsingTimedOut
  194. {
  195. VKLog(@"WARNING: media thumbnailer media parsing timed out");
  196. [_media removeObserver:self forKeyPath:@"parsed"];
  197. [self startFetchingThumbnail];
  198. }
  199. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  200. {
  201. if (object == _media && [keyPath isEqualToString:@"parsed"]) {
  202. if ([_media isParsed]) {
  203. [_parsingTimeoutTimer invalidate];
  204. _parsingTimeoutTimer = nil;
  205. [_media removeObserver:self forKeyPath:@"parsed"];
  206. [self startFetchingThumbnail];
  207. }
  208. return;
  209. }
  210. return [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  211. }
  212. - (void)didFetchThumbnail
  213. {
  214. if (_shouldRejectFrames)
  215. return;
  216. // The video thread is blocking on us. Beware not to do too much work.
  217. _numberOfReceivedFrames++;
  218. float position = libvlc_media_player_get_position(_mp);
  219. long long length = libvlc_media_player_get_length(_mp);
  220. // Make sure we are getting the right frame
  221. if (position < self.snapshotPosition && _numberOfReceivedFrames < 2) {
  222. libvlc_media_player_set_position(_mp, self.snapshotPosition);
  223. return;
  224. }
  225. if ((length < kStandardStartTime * 2 && _numberOfReceivedFrames < 5) && self.snapshotPosition == kSnapshotPosition) {
  226. libvlc_media_player_set_position(_mp, kSnapshotPosition);
  227. return;
  228. }
  229. if ((position <= 0.05 && _numberOfReceivedFrames < 8) && length > 1000) {
  230. // Arbitrary choice to work around broken files.
  231. libvlc_media_player_set_position(_mp, kSnapshotPosition);
  232. return;
  233. }
  234. // it isn't always best what comes first
  235. if (_numberOfReceivedFrames < 4)
  236. return;
  237. NSAssert(_data, @"We have no data");
  238. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  239. const CGFloat width = _effectiveThumbnailWidth;
  240. const CGFloat height = _effectiveThumbnailHeight;
  241. const CGFloat pitch = 4 * width;
  242. CGContextRef bitmap = CGBitmapContextCreate(_data,
  243. width,
  244. height,
  245. 8,
  246. pitch,
  247. colorSpace,
  248. kCGImageAlphaNoneSkipLast);
  249. CGColorSpaceRelease(colorSpace);
  250. NSAssert(bitmap, @"Can't create bitmap");
  251. // Create the thumbnail image
  252. //NSAssert(!_thumbnail, @"We already have a thumbnail");
  253. if (_thumbnail)
  254. CGImageRelease(_thumbnail);
  255. _thumbnail = CGBitmapContextCreateImage(bitmap);
  256. // Put a new context there.
  257. CGContextRelease(bitmap);
  258. // Make sure we don't block the video thread now
  259. [self performSelector:@selector(notifyDelegate) withObject:nil afterDelay:0];
  260. }
  261. - (void)stopAsync
  262. {
  263. if (_mp) {
  264. libvlc_media_player_stop(_mp);
  265. libvlc_media_player_release(_mp);
  266. _mp = NULL;
  267. }
  268. // Now release data
  269. if (_data)
  270. free(_data);
  271. _data = NULL;
  272. _shouldRejectFrames = NO;
  273. }
  274. - (void)endThumbnailing
  275. {
  276. _shouldRejectFrames = YES;
  277. [_thumbnailingTimeoutTimer invalidate];
  278. _thumbnailingTimeoutTimer = nil;
  279. [self performSelectorInBackground:@selector(stopAsync) withObject:nil];
  280. }
  281. - (void)notifyDelegate
  282. {
  283. [self endThumbnailing];
  284. // Call delegate
  285. [_delegate mediaThumbnailer:self didFinishThumbnail:_thumbnail];
  286. }
  287. - (void)mediaThumbnailingTimedOut
  288. {
  289. VKLog(@"WARNING: media thumbnailer media thumbnailing timed out");
  290. [self endThumbnailing];
  291. // Call delegate
  292. [_delegate mediaThumbnailerDidTimeOut:self];
  293. }
  294. @end