CNEditVideoController.m
36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//
// ZLEditVideoController.m
// ZLPhotoBrowser
//
// Created by long on 2017/9/15.
// Copyright © 2017年 long. All rights reserved.
//
#import "CNEditVideoController.h"
#import <AVFoundation/AVFoundation.h>
#import "TZAssetModel.h"
#import <objc/runtime.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "TZImagePickerController.h"
#import "TZPhotoPreviewCell.h"
#import "TZImageCropManager.h"
#define kItemWidth kItemHeight * 2/3
#define kItemHeight 50
#define kAPPName @"网++"
#pragma mark - 显示帧数的CNEditFrameView
@interface CNEditVideoCell : UICollectionViewCell
@property (nonatomic, strong) UIImageView *imageView;
@end
@implementation CNEditVideoCell
- (UIImageView *)imageView
{
if (!_imageView) {
_imageView = [[UIImageView alloc] init];
_imageView.frame = self.bounds;
_imageView.contentMode = UIViewContentModeScaleAspectFill;
_imageView.clipsToBounds = YES;
[self.contentView addSubview:_imageView];
}
return _imageView;
}
@end
#pragma mark - 协议编辑帧数协议CNEditFrameViewDelegate
@protocol CNEditFrameViewDelegate <NSObject>
- (void)editViewValidRectChanged;//有效范围更变
- (void)editViewValidRectEndChanged;//有效范围更变结束
@end
#pragma mark - 编辑时视图CNEditFrameView
@interface CNEditFrameView : UIView
{
UIImageView *_leftView;//左视图
UIImageView *_rightView;//有视图
}
@property (nonatomic, assign) CGRect validRect;
@property (nonatomic, weak) id<CNEditFrameViewDelegate> delegate;
@end
@implementation CNEditFrameView
- (instancetype)init
{
self = [super init];
if (self) {
[self setupUI];
}
return self;
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
//扩大下有效范围
CGRect left = _leftView.frame;
left.origin.x -= kItemWidth/2;
left.size.width += kItemWidth/2;
CGRect right = _rightView.frame;
right.size.width += kItemWidth/2;
if (CGRectContainsPoint(left, point)) {
return _leftView;
}
if (CGRectContainsPoint(right, point)) {
return _rightView;
}
return nil;
}
- (void)setupUI
{
self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.5];
self.layer.borderWidth = 2;
self.layer.borderColor = [UIColor clearColor].CGColor;
_leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"video_edit_left"]];
_leftView.userInteractionEnabled = YES;
_leftView.tag = 0;
UIPanGestureRecognizer *lg = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[_leftView addGestureRecognizer:lg];
[self addSubview:_leftView];
_rightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"video_edit_right"]];
_rightView.userInteractionEnabled = YES;
_rightView.tag = 1;
UIPanGestureRecognizer *rg = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[_rightView addGestureRecognizer:rg];
[self addSubview:_rightView];
}
- (void)panAction:(UIGestureRecognizer *)pan //滑动收拾实现
{
self.layer.borderColor = [[UIColor whiteColor] colorWithAlphaComponent:.4].CGColor;
CGPoint point = [pan locationInView:self];
CGRect rct = self.validRect;
const CGFloat W = self.frame.size.width;
CGFloat minX = 0;
CGFloat maxX = W;
switch (pan.view.tag) {
case 0: {
//left视图响应
maxX = rct.origin.x + rct.size.width - kItemWidth;
point.x = MAX(minX, MIN(point.x, maxX));
point.y = 0;
rct.size.width -= (point.x - rct.origin.x);
rct.origin.x = point.x;
}
break;
case 1:
{
//right视图响应
minX = rct.origin.x + kItemWidth/2;
maxX = W - kItemWidth/2;
point.x = MAX(minX, MIN(point.x, maxX));
point.y = 0;
rct.size.width = (point.x - rct.origin.x + kItemWidth/2);
}
break;
}
switch (pan.state) {
case UIGestureRecognizerStateBegan:
case UIGestureRecognizerStateChanged:
if (self.delegate && [self.delegate respondsToSelector:@selector(editViewValidRectChanged)]) {
[self.delegate editViewValidRectChanged];//滑动响应实现
}
break;
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
self.layer.borderColor = [UIColor clearColor].CGColor;
if (self.delegate && [self.delegate respondsToSelector:@selector(editViewValidRectEndChanged)]) {
[self.delegate editViewValidRectEndChanged];//滑动结束响应实现
}
break;
default:
break;
}
self.validRect = rct;
}
- (void)setValidRect:(CGRect)validRect//根据范围
{
_validRect = validRect;
_leftView.frame = CGRectMake(validRect.origin.x - kItemWidth/4, 0, kItemWidth/2, kItemHeight);
_rightView.frame = CGRectMake(validRect.origin.x+validRect.size.width-kItemWidth/4, 0, kItemWidth/2, kItemHeight);
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, self.validRect);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(context, 4.0);
CGPoint topPoints[2];
topPoints[0] = CGPointMake(self.validRect.origin.x, 0);
topPoints[1] = CGPointMake(self.validRect.origin.x+self.validRect.size.width, 0);
CGPoint bottomPoints[2];
bottomPoints[0] = CGPointMake(self.validRect.origin.x, kItemHeight);
bottomPoints[1] = CGPointMake(self.validRect.origin.x+self.validRect.size.width, kItemHeight);
CGContextAddLines(context, topPoints, 2);
CGContextAddLines(context, bottomPoints, 2);
CGContextDrawPath(context, kCGPathStroke);
}
@end
#pragma mark - 编辑视频控制器CNEditVideoController
@interface CNEditVideoController () <UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, CNEditFrameViewDelegate>
{
UIView *_bottomView;
UIButton *_cancelBtn;
UIButton *_doneBtn;
NSTimer *_timer;
//下方collectionview偏移量
CGFloat _offsetX;
BOOL _orientationChanged;
UIView *_indicatorLine;
AVAsset *_avAsset;
NSTimeInterval _interval;
NSInteger _measureCount;
NSOperationQueue *_queue;
NSMutableDictionary<NSString *, UIImage *> *_imageCache;
NSMutableDictionary<NSString *, NSBlockOperation *> *_opCache;
}
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) CNEditFrameView *editView;
@property (nonatomic, strong) AVAssetImageGenerator *generator;
@end
@implementation CNEditVideoController
- (void)dealloc
{
[_queue cancelAllOperations];
[self stopTimer];
[[NSNotificationCenter defaultCenter] removeObserver:self];
// NSLog(@"---- %s", __FUNCTION__);
}
- (AVAssetImageGenerator *)generator
{
if (!_generator) {
_generator = [[AVAssetImageGenerator alloc] initWithAsset:_avAsset];
_generator.maximumSize = CGSizeMake(kItemWidth*4, kItemHeight*4);
_generator.appliesPreferredTrackTransform = YES;
_generator.requestedTimeToleranceBefore = kCMTimeZero;
_generator.requestedTimeToleranceAfter = kCMTimeZero;
_generator.apertureMode = AVAssetImageGeneratorApertureModeProductionAperture;
}
return _generator;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
[self analysisAssetImages];
_queue = [[NSOperationQueue alloc] init];
_queue.maxConcurrentOperationCount = 3;
_imageCache = [NSMutableDictionary dictionary];
_opCache = [NSMutableDictionary dictionary];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationChanged:) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appResignActive) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[UIApplication sharedApplication].statusBarHidden = YES;
self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
UIEdgeInsets inset = UIEdgeInsetsZero;
if (@available(iOS 11, *)) {
inset = self.view.safeAreaInsets;
}
self.playerLayer.frame = CGRectMake(15, inset.top>0?inset.top:30, [UIScreen mainScreen].bounds.size.width-30, [UIScreen mainScreen].bounds.size.height-160-inset.bottom);
self.editView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-kItemWidth*10)/2, [UIScreen mainScreen].bounds.size.height-100-inset.bottom, kItemWidth*10, kItemHeight);
self.editView.validRect = self.editView.bounds;
self.collectionView.frame = CGRectMake(inset.left, [UIScreen mainScreen].bounds.size.height-100-inset.bottom, [UIScreen mainScreen].bounds.size.width-inset.left-inset.right, kItemHeight);
CGFloat leftOffset = (([UIScreen mainScreen].bounds.size.width-kItemWidth*10)/2-inset.left);
CGFloat rightOffset = (([UIScreen mainScreen].bounds.size.width-kItemWidth*10)/2-inset.right);
[self.collectionView setContentInset:UIEdgeInsetsMake(0, leftOffset, 0, rightOffset)];
[self.collectionView setContentOffset:CGPointMake(_offsetX-leftOffset, 0)];
CGFloat bottomViewH = 44;
CGFloat bottomBtnH = 30;
_bottomView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-bottomViewH-inset.bottom, [UIScreen mainScreen].bounds.size.width, kItemHeight);
_cancelBtn.frame = CGRectMake(10+inset.left, 7, 60, bottomBtnH);
_doneBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-70-inset.right, 7, 60, bottomBtnH);
[self.playerLayer setBackgroundColor:[UIColor clearColor].CGColor];
}
#pragma mark - notifies
//设备旋转
- (void)deviceOrientationChanged:(NSNotification *)notify
{
_offsetX = self.collectionView.contentOffset.x + self.collectionView.contentInset.left;
_orientationChanged = YES;
}
- (void)appResignActive
{
[self stopTimer];
}
- (void)appBecomeActive
{
[self startTimer];
}
- (void)setupUI
{
//禁用返回手势
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.delegate = nil;
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
self.view.backgroundColor = [UIColor blackColor];
self.playerLayer = [[AVPlayerLayer alloc] init];
[self.view.layer addSublayer:self.playerLayer];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.itemSize = CGSizeMake(kItemWidth, kItemHeight);
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 0;
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
self.collectionView.backgroundColor = [UIColor clearColor];
self.collectionView.showsHorizontalScrollIndicator = NO;
[self.collectionView registerClass:CNEditVideoCell.class forCellWithReuseIdentifier:@"CNEditVideoCell"];
[self.view addSubview:self.collectionView];
[self creatBottomView];
self.editView = [[CNEditFrameView alloc] init];
self.editView.delegate = self;
[self.view addSubview:self.editView];
_indicatorLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 2, kItemHeight)];
// _indicatorLine.backgroundColor = [RGBOF(0x0BBE06) colorWithAlphaComponent:.7];
}
- (void)creatBottomView
{
//下方视图
_bottomView = [[UIView alloc] init];
_bottomView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.7];
[self.view addSubview:_bottomView];
_cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
[_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
[_cancelBtn addTarget:self action:@selector(cancelBtn_click) forControlEvents:UIControlEventTouchUpInside];
[_bottomView addSubview:_cancelBtn];
_doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[_doneBtn setTitle:@"完成" forState:UIControlStateNormal];
[_doneBtn setBackgroundColor:[UIColor clearColor]];
// [_doneBtn setTitleColor:RGBOF(0x0BBE06) forState:UIControlStateNormal];
_doneBtn.titleLabel.font = [UIFont systemFontOfSize:15];
_doneBtn.layer.masksToBounds = YES;
_doneBtn.layer.cornerRadius = 3.0f;
[_doneBtn addTarget:self action:@selector(btnDone_click) forControlEvents:UIControlEventTouchUpInside];
[_bottomView addSubview:_doneBtn];
}
#pragma mark - 解析视频每一帧图片
- (void)analysisAssetImages
{
NSTimeInterval duration = 0.0;
if ([self.model.asset isKindOfClass:[PHAsset class]]) {
PHAsset *asset = self.model.asset;
duration = asset.duration;
}else if([self.model.asset isKindOfClass:[ALAsset class]]){
duration = [[self.model.asset valueForProperty:ALAssetPropertyDuration] doubleValue];
}
TZImagePickerController *_tzImagePickerVc = (TZImagePickerController *)self.navigationController;
_interval = _tzImagePickerVc.maxEditVideoTime/10.0;
_measureCount = (NSInteger)(duration / _interval);
///播放视频的
if ([self.model.asset isKindOfClass:[PHAsset class]]) {//PHAsset
__weak typeof(self) weakSelf = self;
[[PHCachingImageManager defaultManager] requestPlayerItemForVideo:self.model.asset options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
dispatch_async(dispatch_get_main_queue(), ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!playerItem) return;
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
strongSelf.playerLayer.player = player;
[strongSelf startTimer];
});
}];
///截取视频帧数
PHVideoRequestOptions* options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestAVAssetForVideo:self.model.asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
__strong typeof(weakSelf) strongSelf = weakSelf;
strongSelf->_avAsset = asset;
dispatch_async(dispatch_get_main_queue(), ^{
[strongSelf.collectionView reloadData];
});
}];
}else if([self.model.asset isKindOfClass:[ALAsset class]]){//ALAsset
///播放视频的
ALAsset *alAsset = (ALAsset *)self.model.asset;
ALAssetRepresentation *defaultRepresentation = [alAsset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[alAsset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:videoURL];
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
self.playerLayer.player = player;
[self startTimer];
///截取视频帧数
NSURL *videoURL_al =[self.model.asset valueForProperty:ALAssetPropertyAssetURL]; // ALAssetPropertyURLs
AVAsset *videoAsset = [AVURLAsset assetWithURL:videoURL];
_avAsset = videoAsset ;
[self.collectionView reloadData];
}
}
#pragma mark - action
- (void)cancelBtn_click
{
[self stopTimer];
if (self.backButtonEditClickBlock) {
TZImagePickerController *_tzImagePickerVc = (TZImagePickerController *)self.navigationController;
self.backButtonEditClickBlock(_tzImagePickerVc.isSelectOriginalPhoto);
}
UIViewController *vc = [self.navigationController popViewControllerAnimated:NO];
if (!vc) {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)btnDone_click
{
[self stopTimer];
TZImagePickerController *_tzImagePickerVc = (TZImagePickerController *)self.navigationController;
[_tzImagePickerVc showProgressHUD];
[self exportEditVideoForAsset:_avAsset range:[self getTimeRange] complete:^(BOOL isSuc, id asset) {
[_tzImagePickerVc hideProgressHUD];
if (isSuc) {
TZAssetModel *editModel = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo];
// 如果没有选中过照片 点击确定时选中当前预览的照片
if (_tzImagePickerVc.selectedModels.count == 0 && _tzImagePickerVc.minImagesCount <= 0) {
[_tzImagePickerVc addSelectedModel:editModel];
}
if (self.doneButtonEditClickBlock) {
self.doneButtonEditClickBlock(_tzImagePickerVc.isSelectOriginalPhoto);
}
[_tzImagePickerVc hideProgressHUD];
}else{
[_tzImagePickerVc showAlertWithTitle:@"编辑失败"];
}
}];
}
#pragma mark - 截取视频
- (void)exportEditVideoForAsset:(AVAsset *)asset range:(CMTimeRange)range complete:(void (^)(BOOL, id))complete
{
[self export:asset range:range presetName:AVAssetExportPresetPassthrough renderSize:CGSizeZero imageSize:CGSizeZero effectImage:nil birthRate:0 velocity:0 complete:^(NSString *exportFilePath, NSError *error) {
if (!error) {
[self saveVideoToAblum:[NSURL fileURLWithPath:exportFilePath] completion:^(BOOL isSuc, id asset) {
dispatch_async(dispatch_get_main_queue(), ^{
if (complete) complete(isSuc, asset);
});
}];
} else {
dispatch_async(dispatch_get_main_queue(), ^{
if (complete) complete(NO, nil);
});
}
}];
}
///保存视频到相册
- (void)saveVideoToAblum:(NSURL *)url completion:(void (^)(BOOL, id))completion
{
if (iOS8Later) {
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusDenied) {
if (completion) completion(NO, nil);
} else if (status == PHAuthorizationStatusRestricted) {
if (completion) completion(NO, nil);
} else {
__block PHObjectPlaceholder *placeholderAsset=nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *newAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
placeholderAsset = newAssetRequest.placeholderForCreatedAsset;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (!success) {
if (completion) completion(NO, nil);
return;
}
PHAsset *asset = [self getAssetFromlocalIdentifier:placeholderAsset.localIdentifier];
PHAssetCollection *desCollection = [self getDestinationCollection];
if (!desCollection) completion(NO, nil);
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[[PHAssetCollectionChangeRequest changeRequestForAssetCollection:desCollection] addAssets:@[asset]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (completion) completion(success, asset);
}];
}];
}
}else{
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary writeVideoAtPathToSavedPhotosAlbum:url completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(@"保存视频出错:%@",error.localizedDescription);
if (completion) {
completion(NO,nil);
}
} else {
[assetLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (completion) {
completion(YES,asset);
}
});
} failureBlock:^(NSError *error) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (completion) {
completion(NO,nil);
}
});
}];
}
}];
}
}
- (PHAsset *)getAssetFromlocalIdentifier:(NSString *)localIdentifier{
if(localIdentifier == nil){
NSLog(@"Cannot get asset from localID because it is nil");
return nil;
}
PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil];
if(result.count){
return result[0];
}
return nil;
}
//获取自定义相册
- (PHAssetCollection *)getDestinationCollection
{
//找是否已经创建自定义相册
PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in collectionResult) {
if ([collection.localizedTitle isEqualToString:kAPPName]) {
return collection;
}
}
//新建自定义相册
__block NSString *collectionId = nil;
NSError *error = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:kAPPName].placeholderForCreatedAssetCollection.localIdentifier;
} error:&error];
if (error) {
return nil;
}
return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].lastObject;
}
- (void)export:(AVAsset *)asset range:(CMTimeRange)range presetName:(NSString *)presetName renderSize:(CGSize)renderSize imageSize:(CGSize)imageSize effectImage:(UIImage *)effectImage birthRate:(NSInteger)birthRate velocity:(CGFloat)velocity complete:(void (^)(NSString *exportFilePath, NSError *error))complete
{
NSString *exportFilePath = [self getVideoExportFilePath];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:presetName];
NSURL *exportFileUrl = [NSURL fileURLWithPath:exportFilePath];
exportSession.outputURL = exportFileUrl;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.timeRange = range;
// exportSession.shouldOptimizeForNetworkUse = YES;
if (!CGSizeEqualToSize(renderSize, CGSizeZero)) {
AVMutableVideoComposition *com = [self getVideoComposition:asset renderSize:renderSize imageSize:imageSize effectImage:effectImage birthRate:birthRate velocity:velocity];
if (!com) {
if (complete) {
complete(nil, [NSError errorWithDomain:@"视频裁剪导出失败" code:-1 userInfo:@{@"message": @"视频对象格式可能有错误,没有检测到视频通道"}]);
}
return;
}
exportSession.videoComposition = com;
}
[exportSession exportAsynchronouslyWithCompletionHandler:^{
BOOL suc = NO;
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Export canceled");
break;
case AVAssetExportSessionStatusCompleted:{
NSLog(@"Export completed");
suc = YES;
}
break;
default:
NSLog(@"Export other");
break;
}
if (complete) {
complete(suc?exportFilePath:nil, suc?nil:exportSession.error);
if (!suc) {
[exportSession cancelExport];
}
}
}];
}
- (NSString *)getVideoExportFilePath
{
NSString *format = @"mp4";
NSString *exportFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [self getUniqueStrByUUID], format]];
return exportFilePath;
}
- (NSString *)getUniqueStrByUUID
{
CFUUIDRef uuidObj = CFUUIDCreate(nil);//create a new UUID
//get the string representation of the UUID
CFStringRef uuidString = CFUUIDCreateString(nil, uuidObj);
NSString *str = [NSString stringWithString:(__bridge NSString *)uuidString];
CFRelease(uuidObj);
CFRelease(uuidString);
return [str lowercaseString];
}
- (AVMutableVideoComposition *)getVideoComposition:(AVAsset *)asset renderSize:(CGSize)renderSize imageSize:(CGSize)imageSize effectImage:(UIImage *)effectImage birthRate:(NSInteger)birthRate velocity:(CGFloat)velocity
{
AVMutableComposition *composition = [AVMutableComposition composition];
//视频通道
AVMutableCompositionTrack *assetVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
//音频通道
AVMutableCompositionTrack *assetAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
NSError *error = nil;
//裁剪时长
CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
AVAssetTrack *videoTrack = [asset tracksWithMediaType:AVMediaTypeVideo].firstObject;//视频
AVAssetTrack *audioTrack = [asset tracksWithMediaType:AVMediaTypeAudio].firstObject;//音频
if (!videoTrack) {
return nil;
}
[assetVideoTrack insertTimeRange:timeRange ofTrack:videoTrack atTime:kCMTimeZero error:&error];
NSLog(@"%@", error);
if (audioTrack) {
[assetAudioTrack insertTimeRange:timeRange ofTrack:audioTrack atTime:kCMTimeZero error:&error];
NSLog(@"%@", error);
}
if (error) {
return nil;
}
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, composition.duration);
//处理视频旋转
AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:assetVideoTrack];
[layerInstruction setOpacity:0.0 atTime:assetVideoTrack.timeRange.duration];
//视频旋转,获取视频旋转角度,然后旋转对应角度,保持视频方向正确
CGFloat degree = [self getVideoDegree:videoTrack];
CGSize naturalSize = assetVideoTrack.naturalSize;
CGAffineTransform mixedTransform = CGAffineTransformIdentity;
//处理renderSize,不能大于视频宽高
CGFloat videoWidth = (degree==0 || degree==M_PI) ? naturalSize.width : naturalSize.height;
CGFloat videoHeight = (degree==0 || degree==M_PI) ? naturalSize.height : naturalSize.width;
CGSize cropSize = CGSizeMake(MIN(videoWidth, renderSize.width), MIN(videoHeight, renderSize.height));
CGFloat x, y;
if (degree == M_PI_2) {
//顺时针 90°
CGAffineTransform t = CGAffineTransformMakeTranslation(naturalSize.height,.0);
CGAffineTransform t1 = CGAffineTransformRotate(t, M_PI_2);
//x为正向下 y为正向左
x = -(videoHeight-cropSize.height)/2;
y = (videoWidth-cropSize.width)/2;
mixedTransform = CGAffineTransformTranslate(t1, x, y);
} else if (degree == M_PI) {
//顺时针 180°
CGAffineTransform t = CGAffineTransformMakeTranslation(naturalSize.width, naturalSize.height);
CGAffineTransform t1 = CGAffineTransformRotate(t, M_PI);
//x为正向左 y为正向上
x = (videoWidth-cropSize.width)/2;
y = (videoHeight-cropSize.height)/2;
mixedTransform = CGAffineTransformTranslate(t1, x, y);
} else if (degree == (M_PI_2 * 3)) {
//顺时针 270°
CGAffineTransform t = CGAffineTransformMakeTranslation(.0, naturalSize.width);
CGAffineTransform t1 = CGAffineTransformRotate(t, M_PI_2*3);
//x为正向上 y为正向右
x = (videoHeight-cropSize.height)/2;
y = -(videoWidth-cropSize.width)/2;
mixedTransform = CGAffineTransformTranslate(t1, x, y);
} else {
//x为正向右 y为正向下
x = -(videoWidth-cropSize.width)/2;
y = -(videoHeight-cropSize.height)/2;
mixedTransform = CGAffineTransformMakeTranslation(x, y);
}
[layerInstruction setTransform:mixedTransform atTime:kCMTimeZero];
//管理所有需要处理的视频
AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
videoComposition.frameDuration = CMTimeMake(1, 30);
videoComposition.renderScale = 1;
videoComposition.renderSize = cropSize;
instruction.layerInstructions = @[layerInstruction];
videoComposition.instructions = @[instruction];
return videoComposition;
}
- (CGFloat)getVideoDegree:(AVAssetTrack *)videoTrack
{
CGAffineTransform tf = videoTrack.preferredTransform;
CGFloat degree = 0;
if (tf.b == 1.0 && tf.c == -1.0) {
degree = M_PI_2;
} else if (tf.a == -1.0 && tf.d == -1.0) {
degree = M_PI;
} else if (tf.b == -1.0 && tf.c == 1.0) {
degree = M_PI_2 * 3;
}
return degree;
}
#pragma mark - timer
- (void)startTimer
{
[self stopTimer];
CGFloat duration = _interval * self.editView.validRect.size.width / (kItemWidth);
_timer = [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(playPartVideo:) userInfo:nil repeats:YES];
[_timer fire];
[[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
_indicatorLine.frame = CGRectMake(self.editView.validRect.origin.x, 0, 4, kItemHeight);
[self.editView addSubview:_indicatorLine];
[UIView animateWithDuration:duration delay:.0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear animations:^{
_indicatorLine.frame = CGRectMake(CGRectGetMaxX(self.editView.validRect)-2, 0, 2, kItemHeight);
} completion:nil];
}
- (void)stopTimer
{
[_timer invalidate];
_timer = nil;
[_indicatorLine removeFromSuperview];
[self.playerLayer.player pause];
}
- (CMTime)getStartTime
{
CGRect rect = [self.collectionView convertRect:self.editView.validRect fromView:self.editView];
CGFloat s = MAX(0, _interval * rect.origin.x / (kItemWidth));
return CMTimeMakeWithSeconds(s, self.playerLayer.player.currentTime.timescale);
}
- (CMTimeRange)getTimeRange
{
CMTime start = [self getStartTime];
CGFloat d = _interval * self.editView.validRect.size.width / (kItemWidth);
CMTime duration = CMTimeMakeWithSeconds(d, self.playerLayer.player.currentTime.timescale);
return CMTimeRangeMake(start, duration);
}
- (void)playPartVideo:(NSTimer *)timer
{
[self.playerLayer.player play];
[self.playerLayer.player seekToTime:[self getStartTime] toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
}
#pragma mark - edit view delegate
- (void)editViewValidRectChanged
{
[self stopTimer];
[self.playerLayer.player seekToTime:[self getStartTime] toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
}
- (void)editViewValidRectEndChanged
{
[self startTimer];
}
#pragma mark - scroll view delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (!self.playerLayer.player || _orientationChanged) {
_orientationChanged = NO;
return;
}
[self stopTimer];
[self.playerLayer.player seekToTime:[self getStartTime] toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate) {
[self startTimer];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self startTimer];
}
#pragma mark - collection view data sources
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _measureCount;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CNEditVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CNEditVideoCell" forIndexPath:indexPath];
UIImage *image = _imageCache[@(indexPath.row).stringValue];
if (image) {
cell.imageView.image = image;
}
return cell;
}
static const char _CNOperationCellKey;
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
if (!_avAsset) return;
if (_imageCache[@(indexPath.row).stringValue] || _opCache[@(indexPath.row).stringValue]) {
return;
}
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSInteger row = indexPath.row;
NSInteger i = row * _interval;
CMTime time = CMTimeMake((i+0.35) * _avAsset.duration.timescale, _avAsset.duration.timescale);
NSError *error = nil;
CGImageRef cgImg = [self.generator copyCGImageAtTime:time actualTime:NULL error:&error];
if (!error && cgImg) {
UIImage *image = [UIImage imageWithCGImage:cgImg];
CGImageRelease(cgImg);
[_imageCache setValue:image forKey:@(row).stringValue];
dispatch_async(dispatch_get_main_queue(), ^{
NSIndexPath *nowIndexPath = [collectionView indexPathForCell:cell];
if (row == nowIndexPath.row) {
[(CNEditVideoCell *)cell imageView].image = image;
} else {
UIImage *cacheImage = _imageCache[@(nowIndexPath.row).stringValue];
if (cacheImage) {
[(CNEditVideoCell *)cell imageView].image = cacheImage;
}
}
});
[_opCache removeObjectForKey:@(row).stringValue];
}
objc_removeAssociatedObjects(cell);
}];
[_queue addOperation:op];
[_opCache setValue:op forKey:@(indexPath.row).stringValue];
objc_setAssociatedObject(cell, &_CNOperationCellKey, op, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
NSBlockOperation *op = objc_getAssociatedObject(cell, &_CNOperationCellKey);
if (op) {
[op cancel];
objc_removeAssociatedObjects(cell);
[_opCache removeObjectForKey:@(indexPath.row).stringValue];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end