-
Notifications
You must be signed in to change notification settings - Fork 25
/
Subtitles.swift
355 lines (262 loc) · 13.1 KB
/
Subtitles.swift
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
//
// MPMoviePlayerController-Subtitles.swift
// MPMoviePlayerController-Subtitles
//
// Created by mhergon on 15/11/15.
// Copyright © 2015 mhergon. All rights reserved.
//
import ObjectiveC
import MediaPlayer
private struct AssociatedKeys {
static var FontKey = "FontKey"
static var ColorKey = "FontKey"
static var ContainerKey = "ContainerKey"
static var SubtitleKey = "SubtitleKey"
static var SubtitleHeightKey = "SubtitleHeightKey"
static var PayloadKey = "PayloadKey"
static var TimerKey = "TimerKey"
}
public class Subtitles {
// MARK: - Properties
fileprivate var parsedPayload: NSDictionary?
// MARK: - Public methods
public init(file filePath: URL, encoding: String.Encoding = String.Encoding.utf8) {
// Get string
let string = try! String(contentsOf: filePath, encoding: encoding)
// Parse string
parsedPayload = Subtitles.parseSubRip(string)
}
public init(subtitles string: String) {
// Parse string
parsedPayload = Subtitles.parseSubRip(string)
}
/// Search subtitles at time
///
/// - Parameter time: Time
/// - Returns: String if exists
public func searchSubtitles(at time: TimeInterval) -> String? {
return Subtitles.searchSubtitles(parsedPayload, time)
}
// MARK: - Private methods
/// Subtitle parser
///
/// - Parameter payload: Input string
/// - Returns: NSDictionary
fileprivate static func parseSubRip(_ payload: String) -> NSDictionary? {
do {
// Prepare payload
var payload = payload.replacingOccurrences(of: "\n\r\n", with: "\n\n")
payload = payload.replacingOccurrences(of: "\n\n\n", with: "\n\n")
payload = payload.replacingOccurrences(of: "\r\n", with: "\n")
// Parsed dict
let parsed = NSMutableDictionary()
// Get groups
let regexStr = "(\\d+)\\n([\\d:,.]+)\\s+-{2}\\>\\s+([\\d:,.]+)\\n([\\s\\S]*?(?=\\n{2,}|$))"
let regex = try NSRegularExpression(pattern: regexStr, options: .caseInsensitive)
let matches = regex.matches(in: payload, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, payload.characters.count))
for m in matches {
let group = (payload as NSString).substring(with: m.range)
// Get index
var regex = try NSRegularExpression(pattern: "^[0-9]+", options: .caseInsensitive)
var match = regex.matches(in: group, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, group.characters.count))
guard let i = match.first else {
continue
}
let index = (group as NSString).substring(with: i.range)
// Get "from" & "to" time
regex = try NSRegularExpression(pattern: "\\d{1,2}:\\d{1,2}:\\d{1,2}[,.]\\d{1,3}", options: .caseInsensitive)
match = regex.matches(in: group, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, group.characters.count))
guard match.count == 2 else {
continue
}
guard let from = match.first, let to = match.last else {
continue
}
var h: TimeInterval = 0.0, m: TimeInterval = 0.0, s: TimeInterval = 0.0, c: TimeInterval = 0.0
let fromStr = (group as NSString).substring(with: from.range)
var scanner = Scanner(string: fromStr)
scanner.scanDouble(&h)
scanner.scanString(":", into: nil)
scanner.scanDouble(&m)
scanner.scanString(":", into: nil)
scanner.scanDouble(&s)
scanner.scanString(",", into: nil)
scanner.scanDouble(&c)
let fromTime = (h * 3600.0) + (m * 60.0) + s + (c / 1000.0)
let toStr = (group as NSString).substring(with: to.range)
scanner = Scanner(string: toStr)
scanner.scanDouble(&h)
scanner.scanString(":", into: nil)
scanner.scanDouble(&m)
scanner.scanString(":", into: nil)
scanner.scanDouble(&s)
scanner.scanString(",", into: nil)
scanner.scanDouble(&c)
let toTime = (h * 3600.0) + (m * 60.0) + s + (c / 1000.0)
// Get text & check if empty
let range = NSMakeRange(0, to.range.location + to.range.length + 1)
guard (group as NSString).length - range.length > 0 else {
continue
}
let text = (group as NSString).replacingCharacters(in: range, with: "")
// Create final object
let final = NSMutableDictionary()
final["from"] = fromTime
final["to"] = toTime
final["text"] = text
parsed[index] = final
}
return parsed
} catch {
return nil
}
}
/// Search subtitle on time
///
/// - Parameters:
/// - payload: Inout payload
/// - time: Time
/// - Returns: String
fileprivate static func searchSubtitles(_ payload: NSDictionary?, _ time: TimeInterval) -> String? {
let predicate = NSPredicate(format: "(%f >= %K) AND (%f <= %K)", time, "from", time, "to")
guard let values = payload?.allValues, let result = (values as NSArray).filtered(using: predicate).first as? NSDictionary else {
return nil
}
guard let text = result.value(forKey: "text") as? String else {
return nil
}
return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
public extension MPMoviePlayerController {
//MARK:- Public properties
var subtitleLabel: UILabel? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleKey) as? UILabel }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
//MARK:- Private properties
fileprivate var subtitleContainer: UIView? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.ContainerKey) as? UIView }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.ContainerKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var subtitleLabelHeightConstraint: NSLayoutConstraint? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey) as? NSLayoutConstraint }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var parsedPayload: NSDictionary? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.PayloadKey) as? NSDictionary }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.PayloadKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var timer: Timer? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.TimerKey) as? Timer }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.TimerKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
//MARK:- Public methods
func addSubtitles() -> Self {
// Get subtitle view
getContainer()
// Create label
addSubtitleLabel()
// Notifications
registerNotifications()
return self
}
func open(file filePath: URL, encoding: String.Encoding = String.Encoding.utf8) {
let contents = try! String(contentsOf: filePath, encoding: encoding)
show(subtitles: contents)
}
func show(subtitles string: String) {
// Parse
parsedPayload = Subtitles.parseSubRip(string)
// Timer
timer = Timer.schedule(repeatInterval: 0.5) { (timer) -> Void in self.searchSubtitles() }
}
//MARK:- Private methods
fileprivate func getContainer() {
for a in view.subviews {
for b in a.subviews {
for c in b.subviews {
if c.tag == 1006 {
subtitleContainer = c
}
}
}
}
}
fileprivate func addSubtitleLabel() {
guard let _ = subtitleLabel else {
// Label
subtitleLabel = UILabel()
subtitleLabel?.translatesAutoresizingMaskIntoConstraints = false
subtitleLabel?.backgroundColor = UIColor.clear
subtitleLabel?.textAlignment = .center
subtitleLabel?.numberOfLines = 0
subtitleLabel?.font = UIFont.boldSystemFont(ofSize: UI_USER_INTERFACE_IDIOM() == .pad ? 40.0 : 22.0)
subtitleLabel?.textColor = UIColor.white
subtitleLabel?.numberOfLines = 0;
subtitleLabel?.layer.shadowColor = UIColor.black.cgColor
subtitleLabel?.layer.shadowOffset = CGSize(width: 1.0, height: 1.0);
subtitleLabel?.layer.shadowOpacity = 0.9;
subtitleLabel?.layer.shadowRadius = 1.0;
subtitleLabel?.layer.shouldRasterize = true;
subtitleLabel?.layer.rasterizationScale = UIScreen.main.scale
subtitleLabel?.lineBreakMode = .byWordWrapping
subtitleContainer?.addSubview(subtitleLabel!)
// Position
var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[l]-(20)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!])
subtitleContainer?.addConstraints(constraints)
constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[l]-(30)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!])
subtitleContainer?.addConstraints(constraints)
subtitleLabelHeightConstraint = NSLayoutConstraint(item: subtitleLabel!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 30.0)
subtitleContainer?.addConstraint(subtitleLabelHeightConstraint!)
return
}
}
fileprivate func registerNotifications() {
// Finished
NotificationCenter.default.addObserver(
forName: NSNotification.Name.MPMoviePlayerPlaybackDidFinish,
object: self,
queue: OperationQueue.main) { (notification) -> Void in
self.subtitleLabel?.isHidden = true
self.timer?.invalidate()
}
// Change
NotificationCenter.default.addObserver(
forName: NSNotification.Name.MPMoviePlayerPlaybackStateDidChange,
object: self,
queue: OperationQueue.main) { (notification) -> Void in
switch self.playbackState {
case .playing:
// Start timer
self.timer = Timer.schedule(repeatInterval: 0.5) { (timer) -> Void in self.searchSubtitles() }
break
default:
// Stop timer
self.timer?.invalidate()
break
}
}
}
fileprivate func searchSubtitles() {
if playbackState == .playing {
guard let label = subtitleLabel else { return }
// Search && show subtitles
subtitleLabel?.text = Subtitles.searchSubtitles(parsedPayload, currentPlaybackTime)
// Adjust size
let baseSize = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let rect = label.sizeThatFits(baseSize)
subtitleLabelHeightConstraint?.constant = rect.height + 5.0
subtitleLabel?.layoutIfNeeded()
}
}
}
// Others
public extension Timer {
class func schedule(repeatInterval interval: TimeInterval, handler: ((Timer?) -> Void)!) -> Timer! {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .commonModes)
return timer
}
}