@g9tm/lynxcontrols-native 2.7.2 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/media.jsx CHANGED
@@ -132,6 +132,49 @@ function G9TrackVideo(props) {
132
132
  }
133
133
  } : {}}/>;
134
134
  }
135
+ function G9ProtectedVideo(props) {
136
+ var _props_rate, _props_fit, _props_className, _props_style;
137
+ const seek = 'number' == typeof props.seek && Number.isFinite(props.seek) ? `${Math.max(0, props.seek)}${void 0 !== props.seekKey ? `|${props.seekKey}` : ''}` : void 0;
138
+ const element = <g9-protected-video src={props.src} paused={false === props.paused ? 'false' : 'true'} {...void 0 !== seek ? {
139
+ seek
140
+ } : {}} rate={String(null != (_props_rate = props.rate) ? _props_rate : 1)} muted={props.muted ? 'true' : 'false'} fit={null != (_props_fit = props.fit) ? _props_fit : 'contain'} protect-window={false === props.protectWindow ? 'false' : 'true'} {...props.id ? {
141
+ id: props.id
142
+ } : {}} className="g9-protected-video__media" style={{
143
+ position: 'absolute',
144
+ left: '0px',
145
+ top: '0px',
146
+ right: '0px',
147
+ bottom: '0px'
148
+ }} {...props.onStatus ? {
149
+ bindstatus: (e)=>{
150
+ var _props_onStatus;
151
+ return null == (_props_onStatus = props.onStatus) ? void 0 : _props_onStatus.call(props, e.detail);
152
+ }
153
+ } : {}} {...props.onProgress ? {
154
+ bindprogress: (e)=>{
155
+ var _props_onProgress;
156
+ return null == (_props_onProgress = props.onProgress) ? void 0 : _props_onProgress.call(props, e.detail);
157
+ }
158
+ } : {}}/>;
159
+ return <view className={null != (_props_className = props.className) ? _props_className : 'g9-protected-video'} style={null != (_props_style = props.style) ? _props_style : {
160
+ position: 'relative',
161
+ width: '100%',
162
+ aspectRatio: '1.7778',
163
+ overflow: 'hidden',
164
+ backgroundColor: '#000'
165
+ }}>
166
+ {element}
167
+ {props.children ? <view style={{
168
+ position: 'absolute',
169
+ left: '0px',
170
+ top: '0px',
171
+ right: '0px',
172
+ bottom: '0px'
173
+ }}>
174
+ {props.children}
175
+ </view> : null}
176
+ </view>;
177
+ }
135
178
  const playerSvg = (body)=>`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#ffffff" stroke="none">${body}</svg>`;
136
179
  const PLAY = playerSvg('<path d="M8 5.14v13.72a1 1 0 0 0 1.52.85l11.2-6.86a1 1 0 0 0 0-1.7L9.52 4.29A1 1 0 0 0 8 5.14z"/>');
137
180
  const PAUSE = playerSvg('<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>');
@@ -286,4 +329,4 @@ function G9VideoPlayer(props) {
286
329
  </view>
287
330
  </view>;
288
331
  }
289
- export { G9TrackVideo, G9VideoPlayer, createNativeMediaProvider, g9VideoTime };
332
+ export { G9ProtectedVideo, G9TrackVideo, G9VideoPlayer, createNativeMediaProvider, g9VideoTime };
@@ -6,8 +6,8 @@
6
6
  # same :path. Its version is the family's (npm run check:versions).
7
7
  Pod::Spec.new do |s|
8
8
  s.name = 'g9lynx-native-swift'
9
- s.version = '2.7.2'
10
- s.summary = 'The Swift views of the G9 <g9-richtext>, <g9-canvas> and <g9-blurhash> Lynx elements (UIKit, Core Text).'
9
+ s.version = '2.8.0'
10
+ s.summary = 'The Swift views of the G9 <g9-richtext>, <g9-canvas>, <g9-blurhash> and <g9-protected-video> Lynx elements.'
11
11
  s.homepage = 'https://github.com/imankari/g9lynxcontrols'
12
12
  s.license = { :type => 'MIT' }
13
13
  s.author = 'G9LynxControls'
@@ -15,6 +15,6 @@ Pod::Spec.new do |s|
15
15
  s.source = { :path => '.' }
16
16
  s.source_files = 'swift/**/*.swift'
17
17
  s.swift_version = '5.9'
18
- s.frameworks = 'UIKit', 'CoreText'
18
+ s.frameworks = 'UIKit', 'CoreText', 'AVFoundation'
19
19
  s.requires_arc = true
20
20
  end
@@ -4,7 +4,7 @@
4
4
  # package version — the family's own LYNX_VERSION (scripts/lynx-version.mjs; npm run check:versions).
5
5
  Pod::Spec.new do |s|
6
6
  s.name = 'g9lynx-native'
7
- s.version = '2.7.2'
7
+ s.version = '2.8.0'
8
8
  s.summary = 'G9 SQLite, host, speech and image native modules, the <g9-video>, <g9-richtext>, <g9-canvas> and <g9-blurhash> elements and the digit-drawing <input>/<textarea> for Lynx (sqlite3, NSUserDefaults, UIKit, AVFoundation, Speech, Core Text, ImageIO, Core Image).'
9
9
  s.homepage = 'https://github.com/imankari/g9lynxcontrols'
10
10
  s.license = { :type => 'MIT' }
@@ -22,8 +22,8 @@ Pod::Spec.new do |s|
22
22
  s.libraries = 'sqlite3'
23
23
  # Speech: G9SpeechModule (dictation; the host's Info.plist carries NSSpeechRecognitionUsageDescription).
24
24
  # Core Text: G9InputUI registers the digit fonts.
25
- # ImageIO, Core Graphics, Core Image: G9ImageModule (decode, draw, redact, encode; G9PhotoEditor, 2.7.2).
26
- s.frameworks = 'UIKit', 'AVFoundation', 'Speech', 'CoreText', 'ImageIO', 'CoreGraphics', 'CoreImage'
25
+ # ImageIO, Core Graphics, Core Image: G9ImageModule (decode, draw, redact, encode; G9PhotoEditor, 2.7.0).
26
+ s.frameworks = 'UIKit', 'AVFoundation', 'Speech', 'CoreText', 'ImageIO', 'CoreGraphics', 'CoreImage', 'Security'
27
27
  # The digit fonts of `g9-digits` (G9InputUI.m; ios/fonts/build-digit-fonts.py, from Vazirmatn, SIL OFL 1.1 — the
28
28
  # license travels with them).
29
29
  s.resource_bundles = { 'G9LynxNativeFonts' => ['fonts/*.ttf', 'fonts/OFL.txt'] }
@@ -0,0 +1,37 @@
1
+ #import <Lynx/LynxUI.h>
2
+ #import <Security/Security.h>
3
+ #import <UIKit/UIKit.h>
4
+
5
+ NS_ASSUME_NONNULL_BEGIN
6
+
7
+ /** What the host's pins decide for a server-trust challenge of `<g9-protected-video>`. */
8
+ typedef NS_ENUM(NSInteger, G9LCTrustDecision) {
9
+ /** The system's evaluation (the default trust store). */
10
+ G9LCTrustDecisionSystem = 0,
11
+ /** Trusted (a pinned certificate matched). */
12
+ G9LCTrustDecisionAccept = 1,
13
+ /** Refused (a pin mismatch). */
14
+ G9LCTrustDecisionReject = 2,
15
+ };
16
+
17
+ /** The host's side of `<g9-protected-video>`: its certificate pins, set once at start-up. */
18
+ @interface G9LCProtectedVideo : NSObject
19
+ /**
20
+ * Decides each server-trust challenge of the playlist, key and segment requests (the app's pins); nil = the system
21
+ * decides. Called on a background queue.
22
+ */
23
+ @property(class, nonatomic, copy, nullable) G9LCTrustDecision (^trustDecider)(SecTrustRef trust, NSString *host, NSInteger port);
24
+ @end
25
+
26
+ /**
27
+ * `<g9-protected-video>` on iOS (2.8.0, G9Hub Plan-V8 row 145): a protected HLS player — AVPlayer in a secure layer that
28
+ * captures leave out, paused and hidden while the screen is recorded or mirrored (`status.captured`), no AirPlay, no
29
+ * picture-in-picture, nothing cached. Attributes (text): `src`, `paused`, `seek`, `rate`, `muted`, `fit`; events
30
+ * `status` and `progress` (the same contract as Android's G9ProtectedVideoUI). The view is G9LCProtectedVideoView
31
+ * (Swift, g9lynx-native-swift). The host registers it on its LynxConfig:
32
+ * `[config registerUI:G9LCProtectedVideoUI.class withName:@"g9-protected-video"]`.
33
+ */
34
+ @interface G9LCProtectedVideoUI : LynxUI <UIView *>
35
+ @end
36
+
37
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,115 @@
1
+ #import "G9LCProtectedVideoUI.h"
2
+ #import <Lynx/LynxEventEmitter.h>
3
+ #import <Lynx/LynxPropsProcessor.h>
4
+ #import <Lynx/LynxUIContext.h>
5
+ #import <Lynx/LynxEvent.h>
6
+
7
+ /// The Swift view (`@objc(G9LCProtectedVideoView)` in video/G9LCProtectedVideoView.swift), reached through the
8
+ /// Objective-C runtime: the class stays internal to its pod, so no generated Swift header is needed.
9
+ @protocol G9LCProtectedVideoViewAPI <NSObject>
10
+ @property(nonatomic, copy, nullable) void (^onEvent)(NSString *name, NSDictionary<NSString *, id> *detail);
11
+ @property(nonatomic, copy, nullable) NSInteger (^trustDecider)(SecTrustRef trust, NSString *host, NSInteger port);
12
+ - (void)applySrc:(nullable NSString *)value;
13
+ - (void)applyPaused:(nullable NSString *)value;
14
+ - (void)applySeek:(nullable NSString *)value;
15
+ - (void)applyRate:(nullable NSString *)value;
16
+ - (void)applyMuted:(nullable NSString *)value;
17
+ - (void)applyFit:(nullable NSString *)value;
18
+ - (void)teardown;
19
+ @end
20
+
21
+ typedef UIView<G9LCProtectedVideoViewAPI> G9LCProtectedVideoViewRef;
22
+
23
+ static G9LCTrustDecision (^G9LCProtectedVideoTrust)(SecTrustRef, NSString *, NSInteger) = nil;
24
+
25
+ @implementation G9LCProtectedVideo
26
+
27
+ + (G9LCTrustDecision (^)(SecTrustRef, NSString *, NSInteger))trustDecider {
28
+ @synchronized(self) {
29
+ return G9LCProtectedVideoTrust;
30
+ }
31
+ }
32
+
33
+ + (void)setTrustDecider:(G9LCTrustDecision (^)(SecTrustRef, NSString *, NSInteger))trustDecider {
34
+ @synchronized(self) {
35
+ G9LCProtectedVideoTrust = [trustDecider copy];
36
+ }
37
+ }
38
+
39
+ @end
40
+
41
+ /// Every attribute as text: Lynx hands an NSString, or an NSNumber when the page wrote a boolean or a number.
42
+ static NSString *_Nullable G9LCText(id _Nullable value) {
43
+ if ([value isKindOfClass:NSString.class]) return value;
44
+ if ([value isKindOfClass:NSNumber.class]) {
45
+ NSNumber *number = value;
46
+ if (strcmp(number.objCType, @encode(BOOL)) == 0 || CFGetTypeID((__bridge CFTypeRef)number) == CFBooleanGetTypeID())
47
+ return number.boolValue ? @"true" : @"false";
48
+ return number.stringValue;
49
+ }
50
+ return nil;
51
+ }
52
+
53
+ @implementation G9LCProtectedVideoUI
54
+
55
+ - (UIView *)createView {
56
+ Class cls = NSClassFromString(@"G9LCProtectedVideoView");
57
+ G9LCProtectedVideoViewRef *view = (G9LCProtectedVideoViewRef *)[[cls alloc] initWithFrame:CGRectZero];
58
+ __weak G9LCProtectedVideoUI *weakSelf = self;
59
+ view.onEvent = ^(NSString *name, NSDictionary<NSString *, id> *detail) {
60
+ [weakSelf send:name detail:detail];
61
+ };
62
+ // read per challenge: the host may set or change its pins after the element was created
63
+ view.trustDecider = ^NSInteger(SecTrustRef trust, NSString *host, NSInteger port) {
64
+ G9LCTrustDecision (^decide)(SecTrustRef, NSString *, NSInteger) = G9LCProtectedVideo.trustDecider;
65
+ return decide ? (NSInteger)decide(trust, host, port) : (NSInteger)G9LCTrustDecisionSystem;
66
+ };
67
+ return view;
68
+ }
69
+
70
+ - (G9LCProtectedVideoViewRef *)player {
71
+ return (G9LCProtectedVideoViewRef *)self.view;
72
+ }
73
+
74
+ LYNX_PROP_SETTER("src", setSrc, id) {
75
+ [self.player applySrc:requestReset ? nil : G9LCText(value)];
76
+ }
77
+
78
+ LYNX_PROP_SETTER("paused", setPaused, id) {
79
+ [self.player applyPaused:requestReset ? nil : G9LCText(value)];
80
+ }
81
+
82
+ LYNX_PROP_SETTER("seek", setSeek, id) {
83
+ [self.player applySeek:requestReset ? nil : G9LCText(value)];
84
+ }
85
+
86
+ LYNX_PROP_SETTER("rate", setRate, id) {
87
+ [self.player applyRate:requestReset ? nil : G9LCText(value)];
88
+ }
89
+
90
+ LYNX_PROP_SETTER("muted", setMuted, id) {
91
+ [self.player applyMuted:requestReset ? nil : G9LCText(value)];
92
+ }
93
+
94
+ LYNX_PROP_SETTER("fit", setFit, id) {
95
+ [self.player applyFit:requestReset ? nil : G9LCText(value)];
96
+ }
97
+
98
+ - (void)send:(NSString *)name detail:(NSDictionary *)detail {
99
+ LynxDetailEvent *event = [[LynxDetailEvent alloc] initWithName:name targetSign:self.sign detail:detail];
100
+ [self.context.eventEmitter dispatchCustomEvent:event];
101
+ }
102
+
103
+ - (void)dealloc {
104
+ // The element is gone: release the player on the main thread (the view may outlive the UI briefly).
105
+ G9LCProtectedVideoViewRef *view = self.player;
106
+ if ([NSThread isMainThread]) {
107
+ [view teardown];
108
+ } else {
109
+ dispatch_async(dispatch_get_main_queue(), ^{
110
+ [view teardown];
111
+ });
112
+ }
113
+ }
114
+
115
+ @end
@@ -0,0 +1,421 @@
1
+ import AVFoundation
2
+ import UIKit
3
+
4
+ /// The view of `<g9-protected-video>` on iOS (2.8.0, G9Hub Plan-V8 row 145; Hub's `G9ProtectedVideoView` brought into
5
+ /// the library). The Objective-C element (G9LCProtectedVideoUI) reaches it through the runtime. An AVPlayer plays a
6
+ /// signed HLS playlist (AES-128 is handled by AVFoundation; every URL, the key's included, is signed, so no headers are
7
+ /// needed) and draws:
8
+ /// - inside a "secure layer": the internal canvas view of a `UITextField` with `isSecureTextEntry`, whose content iOS
9
+ /// leaves out of screenshots, recordings and mirroring (an unofficial technique; when the canvas cannot be found on
10
+ /// the running iOS version the video draws in a plain view and that is logged);
11
+ /// - hidden and paused while the screen is captured (`UIScreen.isCaptured`), back to the page's state afterwards.
12
+ /// TLS server-trust challenges go to the host's `trustDecider` (its certificate pins); left unset, the system decides.
13
+ /// No external playback (AirPlay), no picture-in-picture, nothing cached or downloaded. Main thread.
14
+ ///
15
+ /// Attributes (text): `src`, `paused`, `seek` ("<seconds>" or "<seconds>|<nonce>"), `rate`, `muted`, `fit`. Events
16
+ /// through `onEvent`: `status` `{state, position, duration, error?, captured}` on each change, `progress`
17
+ /// `{position, duration, buffered}` about once a second while playing.
18
+ @objc(G9LCProtectedVideoView)
19
+ final class G9LCProtectedVideoView: UIView, AVAssetResourceLoaderDelegate {
20
+ /// Set by the element: `name`, `detail`.
21
+ @objc var onEvent: ((String, [String: Any]) -> Void)?
22
+
23
+ /// The host's certificate decision for a server-trust challenge: 0 = the system decides, 1 = accept, 2 = reject.
24
+ /// Set by the element from `G9LCProtectedVideo.trustDecider` (the app's pins).
25
+ @objc var trustDecider: ((SecTrust, String, Int) -> Int)?
26
+
27
+ private let secureField = UITextField()
28
+ private var secureHost: UIView = UIView()
29
+ private let playerView = G9LCPlayerLayerView()
30
+
31
+ private var player: AVPlayer?
32
+ private var item: AVPlayerItem?
33
+ private var observations: [NSKeyValueObservation] = []
34
+ private var timeObserver: Any?
35
+ private var itemNotes: [NSObjectProtocol] = []
36
+ private var captureNote: NSObjectProtocol?
37
+ private let loaderQueue = DispatchQueue(label: "g9.protected-video.loader")
38
+
39
+ private var src: String?
40
+ private var preparedSrc: String?
41
+ private var paused = true
42
+ private var seekValue: String?
43
+ private var appliedSeek: String?
44
+ private var rate: Float = 1
45
+ private var muted = false
46
+ private var cover = false
47
+ private var updateScheduled = false
48
+
49
+ private var state = ""
50
+ private var readySent = false
51
+ private var ended = false
52
+ private var failure: String?
53
+ private var captured = false
54
+
55
+ override init(frame: CGRect) {
56
+ super.init(frame: frame)
57
+ clipsToBounds = true
58
+ backgroundColor = .black
59
+ isUserInteractionEnabled = false
60
+ secureHost = G9LCProtectedVideoView.makeSecureHost(secureField)
61
+ secureHost.frame = bounds
62
+ secureHost.autoresizingMask = [.flexibleWidth, .flexibleHeight]
63
+ secureHost.isUserInteractionEnabled = false
64
+ addSubview(secureHost)
65
+ playerView.frame = secureHost.bounds
66
+ playerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
67
+ playerView.playerLayer.videoGravity = .resizeAspect
68
+ secureHost.addSubview(playerView)
69
+ captured = UIScreen.main.isCaptured
70
+ captureNote = NotificationCenter.default.addObserver(
71
+ forName: UIScreen.capturedDidChangeNotification, object: nil, queue: .main
72
+ ) { [weak self] _ in
73
+ self?.captureChanged()
74
+ }
75
+ playerView.isHidden = captured
76
+ }
77
+
78
+ required init?(coder: NSCoder) {
79
+ fatalError("init(coder:) is not used")
80
+ }
81
+
82
+ deinit {
83
+ if let note = captureNote { NotificationCenter.default.removeObserver(note) }
84
+ }
85
+
86
+ /// The secure text field's canvas: `_UITextLayoutCanvasView` (iOS 15+) or `_UITextFieldCanvasView` (earlier) — the
87
+ /// layer iOS excludes from captures while `isSecureTextEntry` is on. Taken out of the field and used as a container.
88
+ private static func makeSecureHost(_ field: UITextField) -> UIView {
89
+ field.isSecureTextEntry = true
90
+ field.isUserInteractionEnabled = false
91
+ let canvas = field.subviews.first { NSStringFromClass(type(of: $0)).contains("CanvasView") }
92
+ ?? (field.layer.sublayers?.first?.delegate as? UIView)
93
+ guard let host = canvas else {
94
+ NSLog("[G9ProtectedVideo] no secure canvas in UITextField on iOS %@: the video draws in a plain layer",
95
+ UIDevice.current.systemVersion)
96
+ return UIView()
97
+ }
98
+ host.subviews.forEach { $0.removeFromSuperview() }
99
+ host.removeFromSuperview()
100
+ host.backgroundColor = .clear
101
+ return host
102
+ }
103
+
104
+ // MARK: - attributes (G9LCProtectedVideoUI)
105
+
106
+ @objc func applySrc(_ value: String?) {
107
+ src = value?.isEmpty == false ? value : nil
108
+ scheduleUpdate()
109
+ }
110
+
111
+ @objc func applyPaused(_ value: String?) {
112
+ paused = G9LCProtectedVideoView.flag(value, fallback: true)
113
+ scheduleUpdate()
114
+ }
115
+
116
+ @objc func applySeek(_ value: String?) {
117
+ seekValue = value?.isEmpty == false ? value : nil
118
+ scheduleUpdate()
119
+ }
120
+
121
+ @objc func applyRate(_ value: String?) {
122
+ let parsed = Float(value?.trimmingCharacters(in: .whitespaces) ?? "") ?? 1
123
+ rate = parsed.isFinite && parsed > 0 ? min(max(parsed, 0.25), 4) : 1
124
+ scheduleUpdate()
125
+ }
126
+
127
+ @objc func applyMuted(_ value: String?) {
128
+ muted = G9LCProtectedVideoView.flag(value, fallback: false)
129
+ scheduleUpdate()
130
+ }
131
+
132
+ @objc func applyFit(_ value: String?) {
133
+ cover = value?.trimmingCharacters(in: .whitespaces).lowercased() == "cover"
134
+ scheduleUpdate()
135
+ }
136
+
137
+ /// The element went away: release the player.
138
+ @objc func teardown() {
139
+ release()
140
+ if let note = captureNote { NotificationCenter.default.removeObserver(note) }
141
+ captureNote = nil
142
+ onEvent = nil
143
+ }
144
+
145
+ static func flag(_ value: String?, fallback: Bool) -> Bool {
146
+ guard let value = value?.trimmingCharacters(in: .whitespaces).lowercased() else { return fallback }
147
+ if value == "true" || value == "1" || value.isEmpty { return true }
148
+ if value == "false" || value == "0" { return false }
149
+ return fallback
150
+ }
151
+
152
+ /// Loopback, a private IPv4 range, `localhost` or an mDNS `*.local` name (plain http is allowed only to these).
153
+ static func isLocal(_ host: String?) -> Bool {
154
+ guard let host = host?.lowercased() else { return false }
155
+ if host == "localhost" || host == "::1" || host.hasSuffix(".local") { return true }
156
+ let parts = host.split(separator: ".").compactMap { Int($0) }
157
+ guard parts.count == 4, parts.allSatisfy({ (0...255).contains($0) }) else { return false }
158
+ return parts[0] == 127 || parts[0] == 10 || (parts[0] == 172 && (16...31).contains(parts[1]))
159
+ || (parts[0] == 192 && parts[1] == 168)
160
+ }
161
+
162
+ // Attributes arrive one setter at a time: apply them together once per main-queue turn.
163
+ private func scheduleUpdate() {
164
+ if updateScheduled { return }
165
+ updateScheduled = true
166
+ DispatchQueue.main.async { [weak self] in self?.update() }
167
+ }
168
+
169
+ private func update() {
170
+ updateScheduled = false
171
+ playerView.playerLayer.videoGravity = cover ? .resizeAspectFill : .resizeAspect
172
+ if src != preparedSrc { prepare() }
173
+ guard let player = player else { return }
174
+ player.isMuted = muted
175
+ // A seek waits for the item to be ready (AVPlayerItem refuses a seek with a completion handler before that).
176
+ if let value = seekValue, value != appliedSeek, item?.status == .readyToPlay {
177
+ appliedSeek = value
178
+ let head = value.split(separator: "|").first ?? ""
179
+ if let seconds = Double(head.trimmingCharacters(in: .whitespaces)), seconds.isFinite {
180
+ seek(to: seconds)
181
+ }
182
+ }
183
+ applyPlayback()
184
+ }
185
+
186
+ /// Plays at `rate` when the page wants it and the screen is not captured; else pauses.
187
+ private func applyPlayback() {
188
+ guard let player = player else { return }
189
+ if paused || captured || failure != nil {
190
+ player.pause()
191
+ } else {
192
+ if ended {
193
+ ended = false
194
+ player.seek(to: .zero)
195
+ }
196
+ activateAudio()
197
+ if #available(iOS 16.0, *) { player.defaultRate = rate }
198
+ player.rate = rate
199
+ }
200
+ report()
201
+ }
202
+
203
+ private func seek(to seconds: Double) {
204
+ guard let player = player else { return }
205
+ var target = max(0, seconds)
206
+ let duration = durationSeconds()
207
+ if duration > 0 { target = min(target, duration) }
208
+ ended = false
209
+ player.seek(to: CMTime(seconds: target, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero) {
210
+ [weak self] _ in
211
+ DispatchQueue.main.async { self?.progress() }
212
+ }
213
+ }
214
+
215
+ /// Sound with the ring/silent switch off — unless a call or a recording owns the session.
216
+ private func activateAudio() {
217
+ let session = AVAudioSession.sharedInstance()
218
+ guard session.category != .playAndRecord else { return }
219
+ try? session.setCategory(.playback, mode: .moviePlayback, options: [])
220
+ try? session.setActive(true)
221
+ }
222
+
223
+ // MARK: - player
224
+
225
+ private func prepare() {
226
+ release()
227
+ preparedSrc = src
228
+ readySent = false
229
+ ended = false
230
+ failure = nil
231
+ appliedSeek = nil
232
+ state = ""
233
+ guard let src = src else { return }
234
+ guard let url = URL(string: src.trimmingCharacters(in: .whitespaces)), let scheme = url.scheme?.lowercased(),
235
+ scheme == "https" || scheme == "http" else {
236
+ fail("invalid-src: not an https URL (plain http only to a local-network host)")
237
+ return
238
+ }
239
+ if scheme == "http" && !G9LCProtectedVideoView.isLocal(url.host) {
240
+ fail("invalid-src: not an https URL (plain http only to a local-network host)")
241
+ return
242
+ }
243
+ setState("loading")
244
+ let asset = AVURLAsset(url: url)
245
+ asset.resourceLoader.setDelegate(self, queue: loaderQueue)
246
+ let item = AVPlayerItem(asset: asset)
247
+ // Nothing kept for later: a small forward buffer, no download.
248
+ item.preferredForwardBufferDuration = 30
249
+ let player = AVPlayer(playerItem: item)
250
+ player.automaticallyWaitsToMinimizeStalling = true
251
+ player.allowsExternalPlayback = false
252
+ self.item = item
253
+ self.player = player
254
+ playerView.playerLayer.player = player
255
+ observations.append(item.observe(\.status, options: [.new]) { [weak self] _, _ in
256
+ DispatchQueue.main.async { self?.itemStatusChanged() }
257
+ })
258
+ observations.append(player.observe(\.timeControlStatus, options: [.new]) { [weak self] _, _ in
259
+ DispatchQueue.main.async { self?.report() }
260
+ })
261
+ let center = NotificationCenter.default
262
+ itemNotes.append(center.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main) { [weak self] _ in
263
+ self?.ended = true
264
+ self?.progress()
265
+ self?.report()
266
+ })
267
+ itemNotes.append(center.addObserver(forName: .AVPlayerItemFailedToPlayToEndTime, object: item, queue: .main) {
268
+ [weak self] note in
269
+ let error = note.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error
270
+ self?.fail(G9LCProtectedVideoView.describe(error))
271
+ })
272
+ timeObserver = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 600), queue: .main) {
273
+ [weak self] _ in
274
+ guard let self = self, self.player?.timeControlStatus == .playing else { return }
275
+ self.progress()
276
+ }
277
+ }
278
+
279
+ private func release() {
280
+ if let timeObserver = timeObserver { player?.removeTimeObserver(timeObserver) }
281
+ timeObserver = nil
282
+ observations.forEach { $0.invalidate() }
283
+ observations.removeAll()
284
+ itemNotes.forEach { NotificationCenter.default.removeObserver($0) }
285
+ itemNotes.removeAll()
286
+ item?.asset.cancelLoading()
287
+ player?.pause()
288
+ player?.replaceCurrentItem(with: nil)
289
+ playerView.playerLayer.player = nil
290
+ player = nil
291
+ item = nil
292
+ preparedSrc = nil
293
+ }
294
+
295
+ private func itemStatusChanged() {
296
+ guard let item = item else { return }
297
+ switch item.status {
298
+ case .failed:
299
+ fail(G9LCProtectedVideoView.describe(item.error))
300
+ case .readyToPlay:
301
+ if !readySent {
302
+ readySent = true
303
+ setState("ready")
304
+ // applies a seek that arrived while loading, then plays or stays paused
305
+ update()
306
+ }
307
+ default:
308
+ break
309
+ }
310
+ }
311
+
312
+ private func captureChanged() {
313
+ captured = UIScreen.main.isCaptured
314
+ playerView.isHidden = captured
315
+ applyPlayback()
316
+ // the page hears the change even when the state word stays the same
317
+ sendStatus()
318
+ }
319
+
320
+ private func fail(_ message: String) {
321
+ failure = message
322
+ player?.pause()
323
+ setState("error")
324
+ }
325
+
326
+ /// The state from the player: one `status` event per change.
327
+ private func report() {
328
+ guard failure == nil, let player = player else { return }
329
+ if !readySent {
330
+ setState("loading")
331
+ return
332
+ }
333
+ if ended {
334
+ setState("ended")
335
+ return
336
+ }
337
+ switch player.timeControlStatus {
338
+ case .playing: setState("playing")
339
+ case .waitingToPlayAtSpecifiedRate: setState("buffering")
340
+ default: setState(state == "ready" && paused ? "ready" : "paused")
341
+ }
342
+ }
343
+
344
+ private func setState(_ next: String) {
345
+ guard next != state else { return }
346
+ state = next
347
+ sendStatus()
348
+ }
349
+
350
+ private func sendStatus() {
351
+ guard !state.isEmpty else { return }
352
+ var detail: [String: Any] = ["state": state, "position": positionSeconds(), "duration": durationSeconds(), "captured": captured]
353
+ if let failure = failure, state == "error" { detail["error"] = failure }
354
+ onEvent?("status", detail)
355
+ }
356
+
357
+ private func progress() {
358
+ onEvent?("progress", ["position": positionSeconds(), "duration": durationSeconds(), "buffered": bufferedSeconds()])
359
+ }
360
+
361
+ private func positionSeconds() -> Double {
362
+ let value = player?.currentTime().seconds ?? 0
363
+ return value.isFinite ? max(0, value) : 0
364
+ }
365
+
366
+ private func durationSeconds() -> Double {
367
+ let value = item?.duration.seconds ?? 0
368
+ return value.isFinite ? max(0, value) : 0
369
+ }
370
+
371
+ /// The end of the loaded range that holds the position.
372
+ private func bufferedSeconds() -> Double {
373
+ guard let item = item else { return 0 }
374
+ let position = positionSeconds()
375
+ var end = position
376
+ for value in item.loadedTimeRanges {
377
+ let range = value.timeRangeValue
378
+ let start = range.start.seconds
379
+ let stop = (range.start + range.duration).seconds
380
+ if start.isFinite, stop.isFinite, start <= position + 0.5, stop > end { end = stop }
381
+ }
382
+ return end
383
+ }
384
+
385
+ private static func describe(_ error: Error?) -> String {
386
+ guard let error = error as NSError? else { return "playback: the video could not be played" }
387
+ return "\(error.domain) \(error.code): \(error.localizedDescription)"
388
+ }
389
+
390
+ // MARK: - AVAssetResourceLoaderDelegate (the host's certificate pins)
391
+
392
+ /// Server-trust challenges of the playlist, key and segment requests: the host's `trustDecider` decides.
393
+ func resourceLoader(
394
+ _ resourceLoader: AVAssetResourceLoader,
395
+ shouldWaitForResponseTo authenticationChallenge: URLAuthenticationChallenge
396
+ ) -> Bool {
397
+ let space = authenticationChallenge.protectionSpace
398
+ guard let decider = trustDecider, space.authenticationMethod == NSURLAuthenticationMethodServerTrust,
399
+ let trust = space.serverTrust, let sender = authenticationChallenge.sender else { return false }
400
+ switch decider(trust, space.host, space.port) {
401
+ case 1:
402
+ sender.use(URLCredential(trust: trust), for: authenticationChallenge)
403
+ case 2:
404
+ sender.cancel(authenticationChallenge)
405
+ default:
406
+ if sender.responds(to: #selector(URLAuthenticationChallengeSender.performDefaultHandling(for:))) {
407
+ sender.performDefaultHandling?(for: authenticationChallenge)
408
+ } else {
409
+ sender.continueWithoutCredential(for: authenticationChallenge)
410
+ }
411
+ }
412
+ return true
413
+ }
414
+ }
415
+
416
+ /// A view whose backing layer is an AVPlayerLayer.
417
+ final class G9LCPlayerLayerView: UIView {
418
+ override class var layerClass: AnyClass { AVPlayerLayer.self }
419
+
420
+ var playerLayer: AVPlayerLayer { layer as! AVPlayerLayer }
421
+ }