VLCMediaThumbnailer.m 11 KB

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