VLCMediaThumbnailer.m 9.3 KB

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