VLCMediaThumbnailer.m 9.2 KB

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