YBIBVideoData.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //
  2. // YBIBVideoData.m
  3. // YBImageBrowserDemo
  4. //
  5. // Created by 波儿菜 on 2019/7/10.
  6. // Copyright © 2019 杨波. All rights reserved.
  7. //
  8. #import "YBIBVideoData.h"
  9. #import "YBIBVideoCell.h"
  10. #import "YBIBVideoData+Internal.h"
  11. #import "YBIBUtilities.h"
  12. #import "YBIBPhotoAlbumManager.h"
  13. #import "YBIBCopywriter.h"
  14. extern CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay);
  15. @interface YBIBVideoData () <NSURLSessionDelegate>
  16. @end
  17. @implementation YBIBVideoData {
  18. NSURLSessionDownloadTask *_downloadTask;
  19. }
  20. #pragma mark - life cycle
  21. - (instancetype)init {
  22. self = [super init];
  23. if (self) {
  24. [self initValue];
  25. }
  26. return self;
  27. }
  28. - (void)initValue {
  29. _loadingFirstFrame = NO;
  30. _loadingAVAssetFromPHAsset = NO;
  31. _downloading = NO;
  32. _interactionProfile = [YBIBInteractionProfile new];
  33. _repeatPlayCount = 0;
  34. _autoPlayCount = 0;
  35. _shouldHideForkButton = NO;
  36. _allowSaveToPhotoAlbum = YES;
  37. }
  38. #pragma mark - load data
  39. - (void)loadData {
  40. // Always load 'thumbImage'.
  41. [self loadThumbImage];
  42. if (self.videoAVAsset) {
  43. [self.delegate yb_videoData:self readyForAVAsset:self.videoAVAsset];
  44. } else if (self.videoPHAsset) {
  45. [self loadAVAssetFromPHAsset];
  46. } else {
  47. [self.delegate yb_videoIsInvalidForData:self];
  48. }
  49. }
  50. - (void)loadAVAssetFromPHAsset {
  51. if (!self.videoPHAsset) return;
  52. if (self.isLoadingAVAssetFromPHAsset) {
  53. self.loadingAVAssetFromPHAsset = YES;
  54. return;
  55. }
  56. self.loadingAVAssetFromPHAsset = YES;
  57. [YBIBPhotoAlbumManager getAVAssetWithPHAsset:self.videoPHAsset completion:^(AVAsset * _Nullable asset) {
  58. YBIB_DISPATCH_ASYNC_MAIN(^{
  59. self.loadingAVAssetFromPHAsset = NO;
  60. self.videoAVAsset = asset;
  61. [self.delegate yb_videoData:self readyForAVAsset:self.videoAVAsset];
  62. [self loadThumbImage];
  63. })
  64. }];
  65. }
  66. - (void)loadThumbImage {
  67. if (self.thumbImage) {
  68. [self.delegate yb_videoData:self readyForThumbImage:self.thumbImage];
  69. } else if (self.projectiveView && [self.projectiveView isKindOfClass:UIImageView.self] && ((UIImageView *)self.projectiveView).image) {
  70. self.thumbImage = ((UIImageView *)self.projectiveView).image;
  71. [self.delegate yb_videoData:self readyForThumbImage:self.thumbImage];
  72. } else {
  73. [self loadThumbImage_firstFrame];
  74. }
  75. }
  76. - (void)loadThumbImage_firstFrame {
  77. if (!self.videoAVAsset) return;
  78. if (self.isLoadingFirstFrame) {
  79. self.loadingFirstFrame = YES;
  80. return;
  81. }
  82. self.loadingFirstFrame = YES;
  83. CGSize containerSize = self.yb_containerSize(self.yb_currentOrientation());
  84. CGSize maximumSize = containerSize;
  85. __weak typeof(self) wSelf = self;
  86. YBIB_DISPATCH_ASYNC(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  87. AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:self.videoAVAsset];
  88. generator.appliesPreferredTrackTransform = YES;
  89. generator.maximumSize = maximumSize;
  90. NSError *error = nil;
  91. CGImageRef cgImage = [generator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:NULL error:&error];
  92. CGImageRef decodedImage = YYCGImageCreateDecodedCopy(cgImage, YES);
  93. UIImage *resultImage = [UIImage imageWithCGImage:decodedImage];
  94. if (cgImage) CGImageRelease(cgImage);
  95. if (decodedImage) CGImageRelease(decodedImage);
  96. YBIB_DISPATCH_ASYNC_MAIN(^{
  97. __strong typeof(wSelf) self = wSelf;
  98. if (!self) return;
  99. self.loadingFirstFrame = NO;
  100. if (!error && resultImage) {
  101. self.thumbImage = resultImage;
  102. [self.delegate yb_videoData:self readyForThumbImage:self.thumbImage];
  103. }
  104. })
  105. })
  106. }
  107. #pragma mark - <YBIBDataProtocol>
  108. @synthesize yb_currentOrientation = _yb_currentOrientation;
  109. @synthesize yb_containerView = _yb_containerView;
  110. @synthesize yb_containerSize = _yb_containerSize;
  111. @synthesize yb_isHideTransitioning = _yb_isHideTransitioning;
  112. @synthesize yb_auxiliaryViewHandler = _yb_auxiliaryViewHandler;
  113. - (nonnull Class)yb_classOfCell {
  114. return YBIBVideoCell.self;
  115. }
  116. - (UIView *)yb_projectiveView {
  117. return self.projectiveView;
  118. }
  119. - (CGRect)yb_imageViewFrameWithContainerSize:(CGSize)containerSize imageSize:(CGSize)imageSize orientation:(UIDeviceOrientation)orientation {
  120. if (containerSize.width <= 0 || containerSize.height <= 0 || imageSize.width <= 0 || imageSize.height <= 0) return CGRectZero;
  121. CGFloat x = 0, y = 0, width = 0, height = 0;
  122. if (imageSize.width / imageSize.height >= containerSize.width / containerSize.height) {
  123. width = containerSize.width;
  124. height = containerSize.width * (imageSize.height / imageSize.width);
  125. x = 0;
  126. y = (containerSize.height - height) / 2.0;
  127. } else {
  128. height = containerSize.height;
  129. width = containerSize.height * (imageSize.width / imageSize.height);
  130. x = (containerSize.width - width) / 2.0;
  131. y = 0;
  132. }
  133. return CGRectMake(x, y, width, height);
  134. }
  135. - (void)yb_preload {
  136. if (!self.delegate) {
  137. [self loadData];
  138. }
  139. }
  140. - (BOOL)yb_allowSaveToPhotoAlbum {
  141. return self.allowSaveToPhotoAlbum;
  142. }
  143. - (void)yb_saveToPhotoAlbum {
  144. void(^unableToSave)(void) = ^(){
  145. [self.yb_auxiliaryViewHandler() yb_showIncorrectToastWithContainer:self.yb_containerView text:[YBIBCopywriter sharedCopywriter].unableToSave];
  146. };
  147. if (self.videoAVAsset && [self.videoAVAsset isKindOfClass:AVURLAsset.class]) {
  148. AVURLAsset *asset = (AVURLAsset *)self.videoAVAsset;
  149. NSURL *URL = asset.URL;
  150. if ([URL.scheme isEqualToString:@"file"]) {
  151. NSString *path = URL.path;
  152. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path)) {
  153. UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(UISaveVideoAtPathToSavedPhotosAlbum_videoPath:didFinishSavingWithError:contextInfo:), nil);
  154. } else {
  155. unableToSave();
  156. }
  157. } else if ([URL.scheme containsString:@"http"]) {
  158. [self downloadWithURL:URL];
  159. } else {
  160. unableToSave();
  161. }
  162. } else {
  163. unableToSave();
  164. }
  165. }
  166. #pragma mark - private
  167. - (void)UISaveVideoAtPathToSavedPhotosAlbum_videoPath:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
  168. if (error) {
  169. [self.yb_auxiliaryViewHandler() yb_showIncorrectToastWithContainer:self.yb_containerView text:[YBIBCopywriter sharedCopywriter].saveToPhotoAlbumFailed];
  170. } else {
  171. [self.yb_auxiliaryViewHandler() yb_showCorrectToastWithContainer:self.yb_containerView text:[YBIBCopywriter sharedCopywriter].saveToPhotoAlbumSuccess];
  172. }
  173. }
  174. - (void)downloadWithURL:(NSURL *)URL {
  175. if (self.isDownloading) {
  176. self.downloading = YES;
  177. return;
  178. }
  179. self.downloading = YES;
  180. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  181. NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  182. _downloadTask = [session downloadTaskWithURL:URL];
  183. [_downloadTask resume];
  184. }
  185. #pragma mark - <NSURLSessionDelegate>
  186. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
  187. didWriteData:(int64_t)bytesWritten
  188. totalBytesWritten:(int64_t)totalBytesWritten
  189. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
  190. CGFloat progress = totalBytesWritten / (double)totalBytesExpectedToWrite;
  191. if (progress < 0) progress = 0;
  192. if (progress > 1) progress = 1;
  193. [self.delegate yb_videoData:self downloadingWithProgress:progress];
  194. }
  195. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
  196. didCompleteWithError:(nullable NSError *)error {
  197. if (error) {
  198. [self.yb_auxiliaryViewHandler() yb_showIncorrectToastWithContainer:self.yb_containerView text:[YBIBCopywriter sharedCopywriter].downloadFailed];
  199. }
  200. self.downloading = NO;
  201. }
  202. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
  203. didFinishDownloadingToURL:(NSURL *)location {
  204. NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  205. NSString *file = [cache stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
  206. [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
  207. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file)) {
  208. UISaveVideoAtPathToSavedPhotosAlbum(file, self, @selector(UISaveVideoAtPathToSavedPhotosAlbum_videoPath:didFinishSavingWithError:contextInfo:), nil);
  209. } else {
  210. [self.yb_auxiliaryViewHandler() yb_showIncorrectToastWithContainer:self.yb_containerView text:[YBIBCopywriter sharedCopywriter].saveToPhotoAlbumFailed];
  211. }
  212. self.downloading = NO;
  213. }
  214. #pragma mark - getters & setters
  215. - (void)setVideoURL:(NSURL *)videoURL{
  216. _videoURL = [videoURL isKindOfClass:NSString.class] ? [NSURL URLWithString:(NSString *)videoURL] : videoURL;
  217. self.videoAVAsset = [AVURLAsset URLAssetWithURL:_videoURL options:nil];
  218. }
  219. - (void)setDownloading:(BOOL)downloading {
  220. _downloading = downloading;
  221. if (downloading) {
  222. [self.delegate yb_videoData:self downloadingWithProgress:0];
  223. } else {
  224. [self.delegate yb_finishDownloadingForData:self];
  225. }
  226. }
  227. - (void)setLoadingAVAssetFromPHAsset:(BOOL)loadingAVAssetFromPHAsset {
  228. _loadingAVAssetFromPHAsset = loadingAVAssetFromPHAsset;
  229. if (loadingAVAssetFromPHAsset) {
  230. [self.delegate yb_startLoadingAVAssetFromPHAssetForData:self];
  231. } else {
  232. [self.delegate yb_finishLoadingAVAssetFromPHAssetForData:self];
  233. }
  234. }
  235. - (void)setLoadingFirstFrame:(BOOL)loadingFirstFrame {
  236. _loadingFirstFrame = loadingFirstFrame;
  237. if (loadingFirstFrame) {
  238. [self.delegate yb_startLoadingFirstFrameForData:self];
  239. } else {
  240. [self.delegate yb_finishLoadingFirstFrameForData:self];
  241. }
  242. }
  243. @synthesize delegate = _delegate;
  244. - (void)setDelegate:(id<YBIBVideoDataDelegate>)delegate {
  245. _delegate = delegate;
  246. if (delegate) {
  247. [self loadData];
  248. }
  249. }
  250. - (id<YBIBVideoDataDelegate>)delegate {
  251. // Stop sending data to the '_delegate' if it is transiting.
  252. return self.yb_isHideTransitioning() ? nil : _delegate;
  253. }
  254. @end