杨锴
2024-08-14 909e20941e45f8712c012db602034b47da0bfdb0
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
//
//  TZVideoCropController.m
//  TZImagePickerController
//
//  Created by 肖兰月 on 2021/5/27.
//  Copyright © 2021 谭真. All rights reserved.
//
 
#import "TZVideoCropController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "UIView+TZLayout.h"
#import "TZImageManager.h"
#import "TZAssetModel.h"
#import "TZImagePickerController.h"
 
@interface TZVideoCropController ()<TZVideoEditViewDelegate,UICollectionViewDelegate, UICollectionViewDataSource> {
    AVPlayer *_player;
    AVPlayerLayer *_playerLayer;
    UIButton *_playButton;
    UIImage *_cover;
    NSString *_outputPath;
    NSString *_errorMsg;
    
    UIButton *_cancelButton;
    UIButton *_doneButton;
    UIProgressView *_progress;
    UILabel *_cropVideoDurationLabel;
    
    AVAssetImageGenerator *_imageGenerator;
    AVAsset *_asset;
    
    CGFloat _collectionViewBeginOffsetX;
    BOOL _isPlayed;
    CGFloat _itemW;
    BOOL _isDraging;
    
    UIStatusBarStyle _originStatusBarStyle;
}
 
// iCloud无法同步提示UI
@property (nonatomic, strong) UIView *iCloudErrorView;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) TZVideoEditView *videoEditView;
@property (strong, nonatomic) NSMutableArray *videoImgArray;
@property (strong, nonatomic) NSArray *imageTimes;
@property (strong, nonatomic) NSTimer *timer;
 
@end
 
@implementation TZVideoCropController
 
#define VideoEditLeftMargin 40
#define PanImageWidth 10
#define MinCropVideoDuration 1
 
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
 
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    [self configMoviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlayer) name:UIApplicationWillResignActiveNotification object:nil];
}
 
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
 
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopTimer];
}
 
- (void)configMoviePlayer {
    [[TZImageManager manager] getPhotoWithAsset:_model.asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
        BOOL iCloudSyncFailed = !photo && [TZCommonTools isICloudSyncError:info[PHImageErrorKey]];
        self.iCloudErrorView.hidden = !iCloudSyncFailed;
        self->_doneButton.enabled = !iCloudSyncFailed;
    }];
    [[TZImageManager manager] getVideoWithAsset:_model.asset completion:^(AVPlayerItem *playerItem, NSDictionary *info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self->_asset = playerItem.asset;
            self->_player = [AVPlayer playerWithPlayerItem:playerItem];
            self->_playerLayer = [AVPlayerLayer playerLayerWithPlayer:self->_player];
            self->_playerLayer.frame = self.view.bounds;
            [self.view.layer addSublayer:self->_playerLayer];
            [self configPlayButton];
            [self configBottomToolBar];
            if (self.imagePickerVc.allowEditVideo) {
                [self configVideoImageCollectionView];
                [self configVideoEditView];
                [self generateVideoImage];
            }
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlayer) name:AVPlayerItemDidPlayToEndTimeNotification object:self->_player.currentItem];
        });
    }];
}
 
- (void)configPlayButton {
    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playButton setImage:[UIImage tz_imageNamedFromMyBundle:@"MMVideoPreviewPlay"] forState:UIControlStateNormal];
    [_playButton setImage:[UIImage tz_imageNamedFromMyBundle:@"MMVideoPreviewPlayHL"] forState:UIControlStateHighlighted];
    [_playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];
}
 
- (void)configBottomToolBar {
    _cropVideoDurationLabel = UILabel.new;
    _cropVideoDurationLabel.textAlignment = NSTextAlignmentCenter;
    _cropVideoDurationLabel.textColor = UIColor.whiteColor;
    _cropVideoDurationLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_cropVideoDurationLabel];
    
    _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_cancelButton setTitle:[NSBundle tz_localizedStringForKey:@"Cancel"] forState:0];
    [_cancelButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];
    
    _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _doneButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_doneButton addTarget:self action:@selector(doneButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_doneButton setTitle:self.imagePickerVc.doneBtnTitleStr forState:UIControlStateNormal];
    [_doneButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [_doneButton setTitleColor:self.imagePickerVc.oKButtonTitleColorDisabled forState:UIControlStateDisabled];
    [self.view addSubview:_doneButton];
    
    if (self.imagePickerVc.videoEditViewPageUIConfigBlock) {
        self.imagePickerVc.videoEditViewPageUIConfigBlock(_playButton, _cropVideoDurationLabel, _cancelButton, _doneButton);
    }
}
 
- (void)configVideoImageCollectionView {
    _itemW = (self.view.tz_width - VideoEditLeftMargin * 2 - 2 * PanImageWidth) / 10.0;
    UICollectionViewFlowLayout *layout = UICollectionViewFlowLayout.new;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(_itemW, _itemW * 2);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.contentInset = UIEdgeInsetsMake(0, VideoEditLeftMargin + PanImageWidth, 0, VideoEditLeftMargin + PanImageWidth);
    _collectionView.clipsToBounds = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.alwaysBounceHorizontal = YES;
    [_collectionView registerClass:TZVideoPictureCell.class forCellWithReuseIdentifier:@"TZVideoPictureCell"];
    [self.view addSubview:_collectionView];
}
 
- (void)configVideoEditView {
    _videoEditView = TZVideoEditView.new;
    _videoEditView.backgroundColor = UIColor.clearColor;
    _videoEditView.delegate = self;
    _videoEditView.maxCropVideoDuration = self.imagePickerVc.maxCropVideoDuration;
    [self.view addSubview:_videoEditView];
}
 
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.imagePickerVc && [self.imagePickerVc isKindOfClass:[TZImagePickerController class]]) {
        return self.imagePickerVc.statusBarStyle;
    }
    return [super preferredStatusBarStyle];
}
 
#pragma mark - Layout
 
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
 
    BOOL isFullScreen = self.view.tz_height == [UIScreen mainScreen].bounds.size.height;
    CGFloat statusBarHeight = isFullScreen ? [TZCommonTools tz_statusBarHeight] : 0;
    CGFloat statusBarAndNaviBarHeight = statusBarHeight + self.navigationController.navigationBar.tz_height;
    
    CGFloat toolBarHeight = 44 + [TZCommonTools tz_safeAreaInsets].bottom;
    CGFloat doneButtonWidth = [_doneButton.currentTitle boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.width;
    doneButtonWidth = MAX(44, doneButtonWidth);
    _cancelButton.frame = CGRectMake(12, self.view.tz_height - toolBarHeight, 44, 44);
    [_cancelButton sizeToFit];
    _cancelButton.tz_height = 44;
    _doneButton.frame = CGRectMake(self.view.tz_width - doneButtonWidth - 12, self.view.tz_height - toolBarHeight, doneButtonWidth, 44);
    _playButton.frame = CGRectMake(0, statusBarAndNaviBarHeight, self.view.tz_width, self.view.tz_height - statusBarAndNaviBarHeight - toolBarHeight);
    
    CGFloat collectionViewH = (self.view.tz_width - VideoEditLeftMargin * 2 - 2 * PanImageWidth) / 10.0 * 2;
    _collectionView.frame = CGRectMake(0, self.view.tz_height - collectionViewH - toolBarHeight - statusBarHeight, self.view.tz_width, collectionViewH);
    _videoEditView.frame = _collectionView.frame;
    _cropVideoDurationLabel.frame = CGRectMake(0, _videoEditView.tz_bottom, self.view.tz_width, 20);
    
    CGFloat playerLayerHeight = CGRectGetMinY(_collectionView.frame) - statusBarHeight * 2;
    CGFloat playerLayerWidth = self.view.tz_width/self.view.tz_height * playerLayerHeight;
    CGFloat playerLayerLeft = (self.view.tz_width - playerLayerWidth) / 2.0;
    CGRect playerLayerFrame = CGRectMake(playerLayerLeft, statusBarHeight, playerLayerWidth, playerLayerHeight);
    _playerLayer.frame = playerLayerFrame;
    _playButton.frame = CGRectMake(0, statusBarAndNaviBarHeight, self.view.tz_width, playerLayerHeight - statusBarAndNaviBarHeight);
   
    if (self.imagePickerVc.videoEditViewPageDidLayoutSubviewsBlock) {
        self.imagePickerVc.videoEditViewPageDidLayoutSubviewsBlock(_playButton, _cropVideoDurationLabel, _cancelButton, _doneButton);
    }
}
 
- (void)generateVideoImage {
    _imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:_asset];
    _imageGenerator.appliesPreferredTrackTransform = YES;
    _imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
    _imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
    _imageGenerator.maximumSize = CGSizeMake(100, 100);
    
    NSTimeInterval durationSeconds = self.model.asset.duration;
    self.videoEditView.videoDuration = durationSeconds;
    
    NSUInteger imageCount = 10;
    CGFloat maxCropWidth = self.view.tz_width - (VideoEditLeftMargin + PanImageWidth) * 2;
    if (durationSeconds <= MinCropVideoDuration) return;
    if (durationSeconds <= self.imagePickerVc.maxCropVideoDuration) {
        imageCount = 10;
        self.videoEditView.allImgWidth = maxCropWidth;
        _cropVideoDurationLabel.text = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Selected for %ld seconds"], (NSInteger)durationSeconds];
    } else {
        CGFloat singleWidthSecond = maxCropWidth / self.imagePickerVc.maxCropVideoDuration;
        CGFloat allImgWidth = singleWidthSecond * durationSeconds;
        self.videoEditView.allImgWidth = allImgWidth;
        imageCount = allImgWidth / _itemW;
        _cropVideoDurationLabel.text = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Selected for %ld seconds"],(long)self.imagePickerVc.maxCropVideoDuration];
    }
    NSArray *assetTracks = [_asset tracksWithMediaType:AVMediaTypeVideo];
    if (!assetTracks.count) {
        self.iCloudErrorView.hidden = NO;
        _doneButton.enabled = NO;
        _cropVideoDurationLabel.hidden = YES;
        return;
    };
    Float64 frameRate = [[_asset tracksWithMediaType:AVMediaTypeVideo][0] nominalFrameRate];;
    NSMutableArray *times = NSMutableArray.array;
    NSTimeInterval intervalSecond = durationSeconds/imageCount;
    CMTime timeFrame;
    for (NSInteger i = 0; i < imageCount; i++) {
        timeFrame = CMTimeMake(intervalSecond * i *frameRate, frameRate);
        NSValue *timeValue = [NSValue valueWithCMTime:timeFrame];
        [times addObject:timeValue];
    }
    self.videoImgArray = NSMutableArray.new;
    self.imageTimes = times;
    typeof(self) weakSelf = self;
    [_imageGenerator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        if (image) {
            UIImage *img = [[UIImage alloc] initWithCGImage:image];
            [weakSelf.videoImgArray addObject:img];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.collectionView reloadData];
            });
        }
    }];
}
 
#pragma mark - UICollectiobViewDataSource & UIcollectionViewDelegate
 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.videoImgArray.count;
}
 
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZVideoPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZVideoPictureCell" forIndexPath:indexPath];
    cell.imgView.image = self.videoImgArray[indexPath.item];
    return cell;
}
 
#pragma mark - UIScrollViewDelegate
 
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!_isDraging) return;
    CGFloat offsetX = scrollView.contentOffset.x;
    if (offsetX - _collectionViewBeginOffsetX >= self.view.tz_width) {
        [self.collectionView setContentOffset:CGPointMake(self.view.tz_width + _collectionViewBeginOffsetX, 0) animated:NO];
    } else if (_collectionViewBeginOffsetX - offsetX >= self.view.tz_width) {
        [self.collectionView setContentOffset:CGPointMake(_collectionViewBeginOffsetX - self.view.tz_width, 0) animated:NO];
    }
    
    [self editViewCropRectBeginChange];
}
 
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _isDraging = YES;
    _collectionViewBeginOffsetX = scrollView.contentOffset.x;
}
 
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _isDraging = NO;
    [self editViewCropRectEndChange];
}
 
#pragma mark - TZVideoEditViewDelegate
 
- (void)editViewCropRectBeginChange {
    [self stopTimer];
    [_playerLayer.player seekToTime:[self getCropStartTime] toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    
    NSTimeInterval second = [self getCropVideoDuration];
    _cropVideoDurationLabel.text = [NSString stringWithFormat:[NSBundle tz_localizedStringForKey:@"Selected for %ld seconds"], (NSInteger)second];
}
 
- (void)editViewCropRectEndChange {
    if (_isPlayed) {
        [self starTimer];
    }
}
 
#pragma mark - Click Event
 
- (void)playButtonClick {
    CMTime currentTime = _player.currentItem.currentTime;
    CMTime durationTime = _player.currentItem.duration;
    if (_player.rate == 0.0f) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TZ_VIDEO_PLAY_NOTIFICATION" object:_player];
        if (currentTime.value == durationTime.value) [_player.currentItem seekToTime:CMTimeMake(0, 1)];
        _isPlayed = YES;
        [self starTimer];
        [_playButton setImage:nil forState:UIControlStateNormal];
    } else {
        _isPlayed = NO;
        [self stopTimer];
        [self pausePlayer];
    }
}
 
- (void)cancelButtonClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}
 
 
- (void)doneButtonClick {
    if ([[TZImageManager manager] isAssetCannotBeSelected:_model.asset]) {
        return;
    }
    [self stopTimer];
    
    TZImagePickerController *imagePickerVc = self.imagePickerVc;
    [imagePickerVc showProgressHUD];
    [[TZImageManager manager] getVideoOutputPathWithAsset:_model.asset presetName:imagePickerVc.presetName timeRange:[self getCropVideoTimeRange] success:^(NSString *outputPath) {
        [imagePickerVc hideProgressHUD];
        self->_outputPath = outputPath;
        [self dismissAndCallDelegateMethod];
    } failure:^(NSString *errorMessage, NSError *error) {
        [imagePickerVc hideProgressHUD];
        self->_errorMsg = errorMessage;
        [self dismissAndCallDelegateMethod];
    }];
}
 
- (void)dismissAndCallDelegateMethod {
    [self dismissViewControllerAnimated:NO completion:^{
        [self callDelegateMethod];
    }];
    [self.imagePickerVc dismissViewControllerAnimated:YES completion:nil];
}
 
- (void)callDelegateMethod {
    if (_outputPath) {
        NSURL *videoURL = [NSURL fileURLWithPath:_outputPath];
        if (self.imagePickerVc.saveEditedVideoToAlbum) {
            [[TZImageManager manager] saveVideoWithUrl:videoURL completion:^(PHAsset *asset, NSError *error) {
                if (error) { // 视频保存失败
                    if ([self.imagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFailToSaveEditedVideoWithError:)]) {
                        [self.imagePickerVc.pickerDelegate imagePickerController:self.imagePickerVc didFailToSaveEditedVideoWithError:error];
                    }
                }
            }];
        }
        UIImage *coverImage = [[TZImageManager manager] getImageWithVideoURL:videoURL];
        if ([self.imagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingAndEditingVideo:outputPath:error:)]) {
            [self.imagePickerVc.pickerDelegate imagePickerController:self.imagePickerVc didFinishPickingAndEditingVideo:coverImage outputPath:_outputPath error:nil];
        }
        if (self.imagePickerVc.didFinishPickingAndEditingVideoHandle) {
            self.imagePickerVc.didFinishPickingAndEditingVideoHandle(coverImage, _outputPath, nil);
        }
    } else {
        if ([self.imagePickerVc.pickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingAndEditingVideo:outputPath:error:)]) {
            [self.imagePickerVc.pickerDelegate imagePickerController:self.imagePickerVc didFinishPickingAndEditingVideo:nil outputPath:nil error:_errorMsg];
        }
        if (self.imagePickerVc.didFinishPickingAndEditingVideoHandle) {
            self.imagePickerVc.didFinishPickingAndEditingVideoHandle(nil, nil, _errorMsg);
        }
    }
}
 
#pragma mark - private method
 
- (CMTime)getCropStartTime {
    NSTimeInterval second = [self getCropVideoStartSecond];
    if (second > self.model.asset.duration) {
        second = roundf(self.model.asset.duration);
    }
    return CMTimeMakeWithSeconds(second, _playerLayer.player.currentTime.timescale);
}
 
- (CMTimeRange)getCropVideoTimeRange {
    NSTimeInterval startSecond = [self getCropVideoStartSecond];
    CMTime start = CMTimeMakeWithSeconds(startSecond, _playerLayer.player.currentTime.timescale);
    NSTimeInterval second = [self getCropVideoDuration];
    CMTime duration = CMTimeMakeWithSeconds(second, _playerLayer.player.currentTime.timescale);
    return CMTimeRangeMake(start, duration);
}
 
- (NSTimeInterval)getCropVideoDuration {
    CGFloat rectW = self.videoEditView.cropRect.size.width;
    CGFloat contentW = self.videoEditView.allImgWidth;
    CGFloat second = rectW / contentW * roundf(self.model.asset.duration);
    return roundf(second);
}
 
- (NSTimeInterval)getCropVideoStartSecond {
    CGFloat offsetX = self.collectionView.contentOffset.x;
    CGFloat contentW = self.videoEditView.allImgWidth;
    CGFloat cropRectX = self.videoEditView.cropRect.origin.x - VideoEditLeftMargin - PanImageWidth;
    NSTimeInterval second = (offsetX + cropRectX) / contentW * roundf(self.model.asset.duration);
    if (second < 0) second = 0;
    return roundf(second);
}
 
- (CMTime)getTimeOfSeek {
    NSTimeInterval second = [self getCropVideoStartSecond];
    if (second > self.model.asset.duration) {
        second = roundf(self.model.asset.duration);
    }
    return CMTimeMakeWithSeconds(second, _playerLayer.player.currentTime.timescale);
}
 
- (void)starTimer {
    [self stopTimer];
    NSTimeInterval timeInterval = [self getCropVideoDuration];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(playCropVideo) userInfo:nil repeats:YES];
    [self.timer fire];
}
 
- (void)stopTimer {
    if (self.timer) {
        [self.videoEditView resetIndicatorLine];
        [_player pause];
        [self.timer invalidate];
        self.timer = nil;
    }
}
 
- (void)playCropVideo {
    [_player seekToTime:[self getCropStartTime] toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    [_player play];
    [self.videoEditView indicatorLineAnimateWithDuration:[self getCropVideoDuration] cropRect:self.videoEditView.cropRect];
}
 
#pragma mark - Notification Method
 
- (void)pausePlayer {
    [_player pause];
    [_playButton setImage:[UIImage tz_imageNamedFromMyBundle:@"MMVideoPreviewPlay"] forState:UIControlStateNormal];
}
 
#pragma mark - lazy
- (UIView *)iCloudErrorView{
    if (!_iCloudErrorView) {
        _iCloudErrorView = [[UIView alloc] initWithFrame:CGRectMake(0, [TZCommonTools tz_statusBarHeight] + 44 + 10, self.view.tz_width, 28)];
        UIImageView *icloud = [[UIImageView alloc] init];
        icloud.image = [UIImage tz_imageNamedFromMyBundle:@"iCloudError"];
        icloud.frame = CGRectMake(20, 0, 28, 28);
        [_iCloudErrorView addSubview:icloud];
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(53, 0, self.view.tz_width - 63, 28);
        label.font = [UIFont systemFontOfSize:10];
        label.textColor = [UIColor whiteColor];
        label.text = [NSBundle tz_localizedStringForKey:@"iCloud sync failed"];
        [_iCloudErrorView addSubview:label];
        [self.view addSubview:_iCloudErrorView];
        _iCloudErrorView.hidden = YES;
    }
    return _iCloudErrorView;
}
 
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
 
- (void)dealloc {
    NSLog(@"%s",__func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
 
#pragma clang diagnostic pop
 
@end
 
 
@implementation TZVideoEditView {
    UILabel *_dragingLabel;
    CGFloat _itemWidth;
    CGFloat _beginOffsetX;
    CGFloat _endOffsetX;
}
 
- (instancetype)initWithFrame:(CGRect)frame {
    self =  [super initWithFrame:frame];
    if (self) {
        [self initSubViews];
    }
    return self;
}
 
- (void)initSubViews {
    _indicatorLine = UIView.new;
    _indicatorLine.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
    [self addSubview:_indicatorLine];
    
    _beginImgView = UIImageView.new;
    _beginImgView.image = [UIImage imageNamed:@"leftVideoEdit"];
    _beginImgView.userInteractionEnabled = YES;
    _beginImgView.tag = 0;
    UIPanGestureRecognizer *beginPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
    [_beginImgView addGestureRecognizer:beginPanGesture];
    [self addSubview:_beginImgView];
    
    _endImgView = UIImageView.new;
    _endImgView.image = [UIImage imageNamed:@"rightVideoEdit"];
    _endImgView.userInteractionEnabled = YES;
    _endImgView.tag = 1;
    UIPanGestureRecognizer *endPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
    [_endImgView addGestureRecognizer:endPanGesture];
    [self addSubview:_endImgView];
}
 
- (void)layoutSubviews {
    _beginImgView.frame = CGRectMake(VideoEditLeftMargin, 0, PanImageWidth, self.tz_height);
    _indicatorLine.frame = CGRectMake(_beginImgView.tz_right - 2, 2, 2, self.tz_height - 4);
    _endImgView.frame = CGRectMake(self.tz_width - PanImageWidth - VideoEditLeftMargin, 0, PanImageWidth, self.tz_height);
    
    self.cropRect =  CGRectMake(VideoEditLeftMargin + PanImageWidth, 0, self.tz_width - VideoEditLeftMargin * 2 - PanImageWidth * 2, self.tz_height);
}
 
- (void)setAllImgWidth:(CGFloat)allImgWidth {
    _allImgWidth = allImgWidth;
    if ((NSInteger)roundf(self.videoDuration) <= 0) {
        self.minCropRectWidth = allImgWidth;
        return;
    }
    
    CGFloat scale = MinCropVideoDuration / self.videoDuration;
    self.minCropRectWidth = scale * allImgWidth;
}
 
- (void)setCropRect:(CGRect)cropRect {
    _cropRect = cropRect;
    self.beginImgView.tz_left = cropRect.origin.x - PanImageWidth;
    self.indicatorLine.tz_left = cropRect.origin.x - self.indicatorLine.tz_width;
    self.endImgView.tz_left = CGRectGetMaxX(cropRect);
 
    [self setNeedsDisplay];
}
 
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    
    CGPoint topPoints[] = {
        CGPointMake(self.cropRect.origin.x, 0),
        CGPointMake(CGRectGetMaxX(self.cropRect), 0)
    };
    CGPoint bottomPoints[] = {
        CGPointMake(self.cropRect.origin.x, self.tz_height),
        CGPointMake(CGRectGetMaxX(self.cropRect), self.tz_height)
    };
 
    CGContextAddLines(context, topPoints, 2);
    CGContextAddLines(context, bottomPoints, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 4.0);
    CGContextDrawPath(context, kCGPathStroke);
}
 
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    CGRect beginImgViewFrame = self.beginImgView.frame;
    beginImgViewFrame.origin.x -= PanImageWidth;
    beginImgViewFrame.size.width += PanImageWidth * 2;
    if (CGRectContainsPoint(beginImgViewFrame, point)) return self.beginImgView;
    
    CGRect endImgViewFrame = self.endImgView.frame;
    endImgViewFrame.origin.x -= PanImageWidth;
    endImgViewFrame.size.width += PanImageWidth * 2;
    if (CGRectContainsPoint(endImgViewFrame, point)) return self.endImgView;
    
    return nil;
}
 
#pragma mark - private
 
- (void)indicatorLineAnimateWithDuration:(NSTimeInterval)duration cropRect:(CGRect)cropRect {
    [self resetIndicatorLine];
    [UIView animateWithDuration:duration delay:.0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.indicatorLine.tz_left = CGRectGetMaxX(cropRect);
    } completion:nil];
}
 
- (void)resetIndicatorLine {
    [self.indicatorLine.layer removeAllAnimations];
    self.indicatorLine.tz_left = CGRectGetMinX(self.cropRect) - self.indicatorLine.tz_width;
}
 
- (void)panGestureAction:(UIGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:self];
    CGRect rect = self.cropRect;
    CGFloat minCropRectLeft = VideoEditLeftMargin + PanImageWidth;
 
    switch (gesture.view.tag) {
        case 0: { // 左边拖拽
            CGFloat maxX = self.endImgView.tz_left - self.minCropRectWidth;
            point.x = MAX(minCropRectLeft, MIN(point.x, maxX));
            point.y = 0;
            
            rect.size.width = CGRectGetMaxX(rect) - point.x;
            rect.origin.x = point.x;
        } break;
        case 1: { // 右边拖拽
            minCropRectLeft = CGRectGetMaxX(self.beginImgView.frame) + self.minCropRectWidth;
            CGFloat  maxX = self.tz_width - VideoEditLeftMargin - PanImageWidth;
 
            point.x = MAX(minCropRectLeft, MIN(point.x, maxX));
            point.y = 0;
 
            rect.size.width = (point.x - rect.origin.x);
        } break;
        default:break;
    }
    
    self.cropRect = rect;
    
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
        case UIGestureRecognizerStateChanged: {
            if (self.delegate && [self.delegate respondsToSelector:@selector(editViewCropRectBeginChange)]) {
                [self.delegate editViewCropRectBeginChange];
            }
        } break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled: {
            if (self.delegate && [self.delegate respondsToSelector:@selector(editViewCropRectEndChange)]) {
                [self.delegate editViewCropRectEndChange];
            }
        } break;
        default: break;
    }
}
 
@end
 
 
 
@implementation TZVideoPictureCell
 
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initSubViews];
    }
    return self;
}
 
- (void)initSubViews {
    _imgView = [[UIImageView alloc] initWithFrame:self.bounds];
    _imgView.contentMode = UIViewContentModeScaleAspectFill;
    _imgView.clipsToBounds = YES;
    [self.contentView addSubview:_imgView];
}
 
@end