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
//
// VIMediaCacheWorker.m
// VIMediaCacheDemo
//
// Created by Vito on 4/21/16.
// Copyright © 2016 Vito. All rights reserved.
//
#import "VIMediaCacheWorker.h"
#import "VICacheAction.h"
#import "VICacheManager.h"
@import UIKit;
static NSInteger const kPackageLength = 204800; // 200kb per package
static NSString *kMCMediaCacheResponseKey = @"kMCMediaCacheResponseKey";
@interface VIMediaCacheWorker ()
@property (nonatomic, strong) NSFileHandle *readFileHandle;
@property (nonatomic, strong) NSFileHandle *writeFileHandle;
@property (nonatomic, strong, readwrite) NSError *setupError;
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, strong) VICacheConfiguration *internalCacheConfiguration;
@property (nonatomic) long long currentOffset;
@property (nonatomic, strong) NSDate *startWriteDate;
@property (nonatomic) float writeBytes;
@property (nonatomic) BOOL writting;
@end
@implementation VIMediaCacheWorker
- (void)dealloc {
[Notification removeObserver:self];
[self save];
[_readFileHandle closeFile];
[_writeFileHandle closeFile];
}
- (instancetype)initWithURL:(NSURL *)url {
self = [super init];
if (self) {
NSString *path = [VICacheManager cachedFilePathForURL:url];
NSFileManager *fileManager = [NSFileManager defaultManager];
_filePath = path;
NSError *error;
NSString *cacheFolder = [path stringByDeletingLastPathComponent];
if (![fileManager fileExistsAtPath:cacheFolder]) {
[fileManager createDirectoryAtPath:cacheFolder
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
if (!error) {
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
}
NSURL *fileURL = [NSURL fileURLWithPath:path];
_readFileHandle = [NSFileHandle fileHandleForReadingFromURL:fileURL error:&error];
if (!error) {
_writeFileHandle = [NSFileHandle fileHandleForWritingToURL:fileURL error:&error];
_internalCacheConfiguration = [VICacheConfiguration configurationWithFilePath:path];
_internalCacheConfiguration.url = url;
}
}
_setupError = error;
}
return self;
}
- (VICacheConfiguration *)cacheConfiguration {
return self.internalCacheConfiguration;
}
- (void)cacheData:(NSData *)data forRange:(NSRange)range {
@synchronized(self.writeFileHandle) {
@try {
[self.writeFileHandle seekToFileOffset:range.location];
[self.writeFileHandle writeData:data];
self.writeBytes += data.length;
[self.internalCacheConfiguration addCacheFragment:range];
} @catch (NSException *exception) {
NSLog(@"write to file error");
}
}
}
- (NSData *)cachedDataForRange:(NSRange)range {
@synchronized(self.readFileHandle) {
@try {
[self.readFileHandle seekToFileOffset:range.location];
NSData *data = [self.readFileHandle readDataOfLength:range.length]; // 空数据也会返回,所以如果 range 错误,会导致播放失效
return data;
} @catch (NSException *exception) {
NSLog(@"read cached data error %@",exception);
}
}
return nil;
}
- (NSArray<VICacheAction *> *)cachedDataActionsForRange:(NSRange)range {
NSArray *cachedFragments = [self.internalCacheConfiguration cacheFragments];
NSMutableArray *actions = [NSMutableArray array];
if (range.location == NSNotFound) {
return [actions copy];
}
NSInteger endOffset = range.location + range.length;
// Delete header and footer not in range
[cachedFragments enumerateObjectsUsingBlock:^(NSValue * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSRange fragmentRange = obj.rangeValue;
NSRange intersectionRange = NSIntersectionRange(range, fragmentRange);
if (intersectionRange.length > 0) {
NSInteger package = intersectionRange.length / kPackageLength;
for (NSInteger i = 0; i <= package; i++) {
VICacheAction *action = [VICacheAction new];
action.actionType = VICacheAtionTypeLocal;
NSInteger offset = i * kPackageLength;
NSInteger offsetLocation = intersectionRange.location + offset;
NSInteger maxLocation = intersectionRange.location + intersectionRange.length;
NSInteger length = (offsetLocation + kPackageLength) > maxLocation ? (maxLocation - offsetLocation) : kPackageLength;
action.range = NSMakeRange(offsetLocation, length);
[actions addObject:action];
}
} else if (fragmentRange.location >= endOffset) {
*stop = YES;
}
}];
if (actions.count == 0) {
VICacheAction *action = [VICacheAction new];
action.actionType = VICacheAtionTypeRemote;
action.range = range;
[actions addObject:action];
} else {
// Add remote fragments
NSMutableArray *localRemoteActions = [NSMutableArray array];
[actions enumerateObjectsUsingBlock:^(VICacheAction * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSRange actionRange = obj.range;
if (idx == 0) {
if (range.location < actionRange.location) {
VICacheAction *action = [VICacheAction new];
action.actionType = VICacheAtionTypeRemote;
action.range = NSMakeRange(range.location, actionRange.location - range.location);
[localRemoteActions addObject:action];
}
[localRemoteActions addObject:obj];
} else {
VICacheAction *lastAction = [localRemoteActions lastObject];
NSInteger lastOffset = lastAction.range.location + lastAction.range.length;
if (actionRange.location > lastOffset) {
VICacheAction *action = [VICacheAction new];
action.actionType = VICacheAtionTypeRemote;
action.range = NSMakeRange(lastOffset, actionRange.location - lastOffset);
[localRemoteActions addObject:action];
}
[localRemoteActions addObject:obj];
}
if (idx == actions.count - 1) {
NSInteger localEndOffset = actionRange.location + actionRange.length;
if (endOffset > localEndOffset) {
VICacheAction *action = [VICacheAction new];
action.actionType = VICacheAtionTypeRemote;
action.range = NSMakeRange(localEndOffset, endOffset - localEndOffset);
[localRemoteActions addObject:action];
}
}
}];
actions = localRemoteActions;
}
return [actions copy];
}
- (void)setContentInfo:(VIContentInfo *)contentInfo {
self.internalCacheConfiguration.contentInfo = contentInfo;
[self.writeFileHandle truncateFileAtOffset:contentInfo.contentLength];
[self.writeFileHandle synchronizeFile];
}
- (void)save {
@synchronized (self.writeFileHandle) {
[self.writeFileHandle synchronizeFile];
[self.internalCacheConfiguration save];
}
}
- (void)startWritting {
if (!self.writting) {
[Notification addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
self.writting = YES;
self.startWriteDate = [NSDate date];
self.writeBytes = 0;
}
- (void)finishWritting {
if (self.writting) {
self.writting = NO;
[Notification removeObserver:self];
NSTimeInterval time = [[NSDate date] timeIntervalSinceDate:self.startWriteDate];
[self.internalCacheConfiguration addDownloadedBytes:self.writeBytes spent:time];
}
}
#pragma mark - Notification
- (void)applicationDidEnterBackground:(NSNotification *)notification {
[self save];
}
@end